15

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:

  • vieportSize which is the size that is used to render, as written in the docs
  • paperSize which is the size of the resulting PDF document
  • and then there is the screen size. phantomjs always fits the width of one screen on the size of the paper. The screen size of my phantomjs version is 1024 x 768 pixels. If the view port is larger than the screen size everything outside the 1024 pixels is not displayed.

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

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

pat
  • 2,600
  • 4
  • 20
  • 21
  • You could manipulate the width of the element/page so that it fits into the document. The question is whether this would still look good. Which phantomjs version and which OS do you use btw? – Artjom B. Jul 02 '14 at 08:18
  • 1
    And I would prefer to not have to design my websites around the requirements of phantomjs... – pat Jul 02 '14 at 08:29
  • Here is another pointer: You could [simulate a page zoom](http://stackoverflow.com/a/9441618/1816580), but this will probably break your page horribly. – Artjom B. Jul 02 '14 at 12:36

1 Answers1

6

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.

Jencel
  • 722
  • 7
  • 17
  • This seems to work well. I do it dynamically using the "evaluate" feature and it works fine, e.g. document.querySelector('body').style.height = "calc(297mm * 1.25)" – Ian Mar 20 '17 at 12:18
  • i used (210 * 1.3) and it came perfect , same as firefox using zoom 130% – Nassim Apr 25 '18 at 10:39