pat
pat

Reputation: 2790

phantomjs fit content to A4 page

I want to convert an HTML page to an A4 sized PDF.

page.paperSize = {
  format: 'A4',
  orientation: 'portrait',
  border: '1cm'
};

Is there a way to scale the website to fit the width of A4?

If I have the following HTML:

<div style="width:1500px; text-align:right;">
  right 1500px
</div>

The right end of the div falls off the page.

I have played with the viewportSize property:

page.viewportSize = {
  width: 480,
  height: 800
};

I would have expected that a larger viewport width results in a a larger part of the page being rendered into the PDF.

page.zoom

Did also not have the desired effect.

The PDF files are reports. For a professional look they should be A4 and not any arbitrary size.

Or is phantomjs the wrong tool for my problem?

I am using phantomjs version 1.9.7 on Ubuntu 12.04.4.


Edit:

It seems that there are three different dimensions here:

I did not find a way yet to change the screen size.

I found this by rendering http://www.whatismyscreenresolution.com/ to PDF.

Upvotes: 16

Views: 9684

Answers (1)

Jencel
Jencel

Reputation: 794

One solution is to create an element that is exactly the same size as A4, and place your content in it. This worked on my machine:

.page{
    position:relative;
    border: 0px;
    width:calc(210mm * 1.25);
    height:calc(297mm * 1.25);
    padding:0
}

Note that I use a zoom factor of 1.25. This is due to this issue.

Upvotes: 6

Related Questions