node.js 16 PDF文件操作神器 html-pdf

上一篇:

幾乎所有的項目涉及到報表或者合同處理等,都會跟PDF打交道。


node.js 16 PDF文件操作神器 html-pdf

pdf

node.js中,用的比較多的是html-pdf,每週下載量達到8萬多,是比較多了。


node.js 16 PDF文件操作神器 html-pdf

html-pdf

這款工具的特點是不光可以通過代碼調用API生成pdf,還提供命令行工具html-pdf來將html文件轉換成pdf文件。

接下來,我們看一下html-pdf的安裝使用。

html-pdf 安裝

<code> npm install -g html-pdf/<code>

由於html-pdf是基於phantomjs的,所以在安裝過程中會自動下載phantomjs。

html-pdf命令行

<code>html-pdf test/businesscard.html businesscard.pdf/<code>

直接運行html-pdf加上源html文件,後面加上pdf文件名就可以生成pdf文件。

創建PDF文件,代碼示例

<code>//引入fs, html-pef模塊
var fs = require('fs');
var pdf = require('html-pdf');
//讀取html文件
var html = fs.readFileSync('./test/businesscard.html', 'utf8');
//參數options, 將PDF format設為letter, 如果是A4,直接將下面代碼中的letter換成A4即可
var options = { format: 'Letter' };

//創建pdf文件
pdf.create(html, options).toFile('./businesscard.pdf', function(err, res) {
if (err) return console.log(err);
console.log(res); // { filename: '/app/businesscard.pdf' }
});/<code>

相關API

<code>var pdf = require('html-pdf');
pdf.create(html).toFile([filepath, ]function(err, res){
console.log(res.filename);
});

pdf.create(html).toStream(function(err, stream){
stream.pipe(fs.createWriteStream('./foo.pdf'));
});

pdf.create(html).toBuffer(function(err, buffer){
console.log('This is a buffer:', Buffer.isBuffer(buffer));
});/<code>

HTML中的header 和footer可以直接讀出

html-pdf 可以將html中的header和footer讀出。只要是id為pageHeader或者pageFooter的都可以被識別出來。

<code>
Header on first page

Header on second page

Header on third page

Header on last page

...



/<code>

關於參數options

在調用API pdf.create(html, options).toFile()創建PDF時,這裡面的參數options相當強大,可以傳很多數據。包括之前說的A4格式。

<code>config = {

// Export options
"directory": "/tmp", // The directory the file gets written into if not using .toFile(filename, callback). default: '/tmp'

// Papersize Options: http://phantomjs.org/api/webpage/property/paper-size.html
"height": "10.5in", // allowed units: mm, cm, in, px
"width": "8in", // allowed units: mm, cm, in, px
- or -
"format": "Letter", // allowed units: A3, A4, A5, Legal, Letter, Tabloid
"orientation": "portrait", // portrait or landscape

// Page options
"border": "0", // default is 0, units: mm, cm, in, px
- or -
"border": {
"top": "2in", // default is 0, units: mm, cm, in, px
"right": "1in",
"bottom": "2in",
"left": "1.5in"
},

paginationOffset: 1, // Override the initial pagination number
"header": {
"height": "45mm",
"contents": '
Author: Marc Bachmann
'
},
"footer": {
"height": "28mm",
"contents": {
first: 'Cover page',
2: 'Second page', // Any page number is working. 1-based index
default: '{{page}}/{{pages}}', // fallback value
last: 'Last Page'
}
},


// Rendering options
"base": "file:///home/www/your-asset-path", // Base path that's used to load files (images, css, js) when they aren't referenced using a host

// Zooming option, can be used to scale images if `options.type` is not pdf
"zoomFactor": "1", // default is 1

// File options
"type": "pdf", // allowed file types: png, jpeg, pdf
"quality": "75", // only used for types png & jpeg

// Script options
"phantomPath": "./node_modules/phantomjs/bin/phantomjs", // PhantomJS binary which should get downloaded automatically
"phantomArgs": [], // array of strings used as phantomjs args e.g. ["--ignore-ssl-errors=yes"]
"script": '/url', // Absolute path to a custom phantomjs/> "timeout": 30000, // Timeout that will cancel phantomjs, in milliseconds

// Time we should wait after window load
// accepted values are 'manual', some delay in milliseconds or undefined to wait for a render event
"renderDelay": 1000,

// HTTP Headers that are used for requests
"httpHeaders": {
// e.g.
"Authorization": "Bearer ACEFAD8C-4B4D-4042-AB30-6C735F5BAC8B"
},

// To run Node application as Windows service
"childProcessOptions": {
"detached": true
}

// HTTP Cookies
"httpCookies": [
// e.g.
{
"name": "Valid-Cookie-Name", // required
"value": "Valid-Cookie-Value", // required
"domain": "localhost",
"path": "/foo", // required
"httponly": true,
"secure": false,
"expires": (new Date()).getTime() + (1000 * 60 * 60) // e.g. expires in 1 hour
}
]

}/<code>


分享到:


相關文章: