Bharat Bhushan
Bharat Bhushan

Reputation: 2097

how to set dpi using phantomjs node?

I am using phantomjs node module. below is the link where from i get this module.

https://github.com/sgentle/phantomjs-node

this really work nice when i create a jpg image file from html. but its default "dpi" is 72 which is not good for printing the image file. so i want to set the dpi when i rendering the image.

from the above link i read some example like page.set('viewportSize', {width:640,height:480}). its set the image size perfectly. but i want to set dpi of image please guide me how can i achieve this.

var phantom = require('phantom');

phantom.create(function (ph) {
  ph.createPage(function (page) {
    page.open("http://www.google.com", function (status) {
       page.render("bla.jpg");
        ph.exit();

    });
  });
});  

Upvotes: 8

Views: 10796

Answers (2)

Taugenichts
Taugenichts

Reputation: 1365

My solution was to not use the in phantom pdf rendering process, because the quality of the generated pdfs is unacceptably bad.

First I generate the image at whatever resolution I need for the required dpi. For me this was 3300x2550 (11in x 8.5in at 300dpi) and used a page zoom factor of 2.364 (closest approximation of a divisor of 11 because we use 11pt font to 2550/1080; 26/11) to keep the same approximate font size as on 1080p. Then I use an external utility (iText or Aspose for example) to push the generated image into a pdf. It prints beautifully and looks good in the pdf. The only problem I have is the storage space is somewhat substantial because a 3300x2550 image file is generated on each run.

Upvotes: -1

Artjom B.
Artjom B.

Reputation: 61952

There are two ways.

1. Zoom

You can use page.zoomFactor to zoom the page. You have to increase the viewport size accordingly before changing the zoomFactor:

page.viewportSize = { width: 1600, height: 800 };
page.zoomFactor = 300.0/72.0;
page.render("zoom4.jpg");

2. PDF

If you are concerned with the quality, then render a pdf of the page. A pdf is vector-based and you can zoom in as much as you like. It works by using the pdf extension when you give the filename to render:

page.render("bla.pdf");

You can see how the rasterize.js example deals with the page sizes. There are some caveats though. You have to keep in mind to adjust the width of the rendered pdf. See for example this (unanswered) question.

Upvotes: 7

Related Questions