Fit content width-wise in pdf

2019-07-06 07:02发布

问题:

When rendering to pdf, I need the html page to be 100% of the print width. Otherwise content gets cut off. Is there an easy way to do this?

I came up with a work-around, which gets the html width after rendering and then sets the zoom factor to force the correct width.

var page = require('webpage').create(),
    system = require('system'),
    dpi = 89.9, // strange, but that's what I get on Mac
    pageWidth = 210; // in mm

var getWidth = function() {
    return page.evaluate(function() {
        // get width manually
        // ...
        return width;
    });
};

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

page.open(system.args[1], function (status) {
    window.setTimeout(function () {
        page.zoomFactor = (pageWidth / 25.4) * dpi / getWidth();
        page.render(system.args[2]);
        phantom.exit();
    }, 200);
});

Looking for a straight forward solution, because getting the width requires me to do some tricks due to the framework I use.

回答1:

Managed to solve this by adding the following CSS rule which will zoom out the page and make it fit:

 html {
    zoom: 0.60; 
  }


回答2:

Edit rasterize.js as follows.

Make a backup of rasterize.js

Remove this block (approx. line 18-31)

if (system.args.length > 4) {
    page.zoomFactor = system.args[4];
}
page.open(address, function (status) {
    if (status !== 'success') {
        console.log('Unable to load the address!');
        phantom.exit();
    } else {
        window.setTimeout(function () {
            page.render(output);
            phantom.exit();
        }, 200);
    }
});

Replace it with this code block

 if (system.args.length > 4) {
        page.zoomFactor = parseFloat(system.args[4].split("=")[1]);
 }
 page.open(address, function (status) {
        if (status !== 'success') {
            console.log('Unable to load the address!');
            phantom.exit(1);
        } else {
            window.setTimeout(function () {
console.log("zoomFactor: " + page.zoomFactor);
      page.evaluate(function(zoom) {
        return document.querySelector('body').style.zoom = zoom;
    }, page.zoomFactor); // <-- your zoom here
                page.render(output);
                phantom.exit();
            }, 200);
        }
    });

Then you can export html to pdf on-the-fly like this:

~/bin/phantomjs ~/bin/phantomjs/examples/rasterize.js \ 
'http://example.com/index.html' \ 
mysite.pdf paperformat=A4 zoom=0.4


标签: pdf phantomjs