基於Phantomjs產生PDF的實現方法_javascript技巧

來源:互聯網
上載者:User

本文執行個體講述了基於Phantomjs產生PDF的實現方法。分享給大家供大家參考,具體如下:

最近在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去定位文字.這點還好因為這個頁面上使用者不會看的。

更多關於JavaScript相關內容感興趣的讀者可查看本站專題:《JavaScript切換特效與技巧總結》、《JavaScript尋找演算法技巧總結》、《JavaScript動畫特效與技巧匯總》、《JavaScript錯誤與調試技巧總結》、《JavaScript資料結構與演算法技巧總結》、《JavaScript遍曆演算法與技巧總結》及《JavaScript數學運算用法總結》

希望本文所述對大家JavaScript程式設計有所協助。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.