生成PDF的新選擇-Phantomjs


最近在node.js項目開發中,遇見生成PDF的需求,當然生成PDF不是一個新意的需求;我可以選擇利用開源的pdfkit或者其他node pdf模塊,或者通過edge.js調用.net/python下的pdf庫去做生成pdf。但是在我看來對於這些東西不管如何也需要花費我們太多的時間(pdf報表的內容報表很復雜),不如把所有的畫圖實現邏輯推向大家所熟悉的html+css來的簡潔,快速,這樣對於pdf格式變化和圖形計算邏輯的變化推到ejs、jade之類的模板引擎,對於以后的修改維護擴展是個很不錯的選擇。所以選擇phantomjs加載頁面生成PDF對於我來說不是個不錯的選擇,同時對於html+css我所需要兼容的僅有webkit一種瀏覽器,沒有厭惡的瀏覽器兼容性顧慮。所以說做就做,我在項目上花了半個小時配置phantomjs的自動化腳本(在各環境能夠自動勾踐),以及實現了一個簡單頁面的PDF轉化。

rasterize.js(來自官方pdf demo):

var page = require('webpage').create(),

        system = require('system'),

        address, output, size;

 

    if (system.args.length < 3 || system.args.length > 5) {

        console.log('Usage: rasterize.js URL filename [paperwidth*paperheight|paperformat] [zoom]');

        console.log('  paper (pdf output) examples: "5in*7.5in", "10cm*20cm", "A4", "Letter"');

        phantom.exit(1);

    } else {

        address = system.args[1];

        output = system.args[2];

        page.viewportSize = { width: 600, height: 600 };

        if (system.args.length > 3 && system.args[2].substr(-4) === ".pdf") {

            size = system.args[3].split('*');

            page.paperSize = size.length === 2 ? { width: size[0], height: size[1], margin: '0px' }

                : { format: system.args[3], orientation: 'portrait', margin: '1cm' };

        }

        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();

                });

            }

        });

    }

 

在node調用端,使用exec調用命令行輸入得到文件並返回到node response流:

guid utils:

 'use strict';

 

    var guid = function () {

        var uid = 0;

        this.newId = function () {

            uid = uid % 1000;

            var now = new Date();

            var utc = new Date(now.getTime() + now.getTimezoneOffset() * 60000);

            return utc.getTime() + uid++;

        }

    }

 

    exports.utils = {

        guid: new guid()

    };

pdfutil:

    'use strict';

 

    var exec = require('child_process').exec;

    var utils = require('./utils').utils;

    var nodeUtil = require('util');

 

    var outPut = function (id, req, res) {

        var path = nodeUtil.format("tmp/%s.pdf", utils.guid.newId());

        var port = req.app.settings.port;

        var pdfUrl = nodeUtil.format("%s://%s%s/pdf/%s", req.protocol, req.host, ( port == 80 || port == 443 ? '' : ':' + port ), id);

 

        exec(nodeUtil.format("phantomjs tool/rasterize.js %s %s A4", pdfUrl, path), function (error, stdout, stderr) {

            if (error || stderr) {

                res.send(500, error || stderr);

                return;

            }

            res.set('Content-Type', 'application/pdf');

            res.download(path);

        });

 

    };

 

    exports.pdfUtils = {

        outPut: outPut

    };

 

響應的代碼也可以很好的轉換為java/c#...的命令行調用來得到pdf並推送到response流中。一切都這么簡單搞定。

node也有node-phantom模塊,但是用它生成的pdf樣式有點怪,所以最后還是堅持采用了exec方式去做。

還有就是phantomjs生成PDF不會把css的背景色和背景圖片帶進去,所以對於這塊專門利用了純色圖片img標簽,並position:relative或者absolute去定位文字.這點還好因為這個頁面上用戶不會看的,

文章也到此結尾,希望多多交流,繼續關注,謝謝大家。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM