Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

  • 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.

like image 217
pat Avatar asked Jul 02 '14 07:07

pat


1 Answers

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.

like image 154
Boris Marinov Avatar answered Sep 30 '22 18:09

Boris Marinov