龙空技术网

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

IT人Vincent 825

前言:

此刻小伙伴们对“node图片转pdf”大致比较看重,各位老铁们都需要知道一些“node图片转pdf”的相关资讯。那么小编在网摘上汇集了一些对于“node图片转pdf””的相关内容,希望兄弟们能喜欢,兄弟们一起来了解一下吧!

上一篇:node.js 15 如何操作Excel文件

几乎所有的项目涉及到报表或者合同处理等,都会跟PDF打交道。

pdf

node.js中,用的比较多的是html-pdf,每周下载量达到8万多,是比较多了。

html-pdf

这款工具的特点是不光可以通过代码调用API生成pdf,还提供命令行工具html-pdf来将html文件转换成pdf文件。

接下来,我们看一下html-pdf的安装使用。

html-pdf 安装

 npm install -g html-pdf

由于html-pdf是基于phantomjs的,所以在安装过程中会自动下载phantomjs。

html-pdf命令行

html-pdf test/businesscard.html businesscard.pdf

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

创建PDF文件,代码示例

//引入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' }});
相关API
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));});
HTML中的header 和footer可以直接读出

html-pdf 可以将html中的header和footer读出。只要是id为pageHeader或者pageFooter的都可以被识别出来。

<div id="pageHeader">Default header</div><div id="pageHeader-first">Header on first page</div><div id="pageHeader-2">Header on second page</div><div id="pageHeader-3">Header on third page</div><div id="pageHeader-last">Header on last page</div>...<div id="pageFooter">Default footer</div><div id="pageFooter-first">Footer on first page</div><div id="pageFooter-2">Footer on second page</div><div id="pageFooter-last">Footer on last page</div>
关于参数options

在调用API pdf.create(html, options).toFile()创建PDF时,这里面的参数options相当强大,可以传很多数据。包括之前说的A4格式。

config = {  // Export options  "directory": "/tmp",       // The directory the file gets written into if not using .toFile(filename, callback). default: '/tmp'  // Papersize Options:   "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": '<div style="text-align: center;">Author: Marc Bachmann</div>'  },  "footer": {    "height": "28mm",    "contents": {      first: 'Cover page',      2: 'Second page', // Any page number is working. 1-based index      default: '<span style="color: #444;">{{page}}</span>/<span>{{pages}}</span>', // fallback value      last: 'Last Page'    }  },  // Rendering options  "base": ";, // 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 script, use the file in lib/scripts as example  "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    }  ]}

标签: #node图片转pdf #node excel转pdf