DIV CSS 佈局教程網

用 PhantomJS 把網頁渲染成 PDF 的實踐
編輯:關於JavaScript     

最近在 Node.js 項目裡遇到生成 PDF 的需求。這不算新鮮事,可選方案不少:pdfkit 這類 Node 模塊,或者通過 edge.js 調用 .NET / Python 下的 PDF 庫。但報表內容實在複雜,無論選哪條路都要投入不少時間。

於是我換了個思路:與其用編程接口一塊塊畫圖,不如把繪製邏輯交給大家最熟悉的 HTML + CSS。這樣報表的格式變化和圖形計算都能推給 EJS、Jade 之類的模板引擎,後續修改、維護、擴展都輕鬆得多。同時,我只需要兼容 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();
      });
    }
  });
}

生成唯一文件名

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

Node 端調用

通過 exec 調命令行生成文件,再把文件流回給 response:

'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 流裡。

幾個實踐中要注意的坑

1. node-phantom 的樣式問題。項目裡也有 node-phantom 模塊可用,但它生成的 PDF 樣式有點怪,所以最後還是選擇直接用 exec 調命令行,可控性更好。

2. 背景色和背景圖不會被渲染。PhantomJS 生成 PDF 時不會帶上 CSS 的 background-color 和 background-image。我的應對辦法是改用純色圖片的 img 標籤,再用 position: relative 或 absolute 去定位文字。好在這一頁用戶本身看不到,只是給 PDF 用的,所以可以接受。

整體看下來,「HTML/CSS 排版 + PhantomJS 渲染」這條路最吸引人的地方在於:後續改版式就是改模板,不用碰任何繪圖代碼。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved