最近写了一个小功能模块,将html文件转化为pdf文件。
1.需求
现在有这么一个需求:
假设App里面有一份html格式的劳动合同, 需要点击某按钮生成对应的pdf文件保存起来。如图:
这就需要后端来处理,后端为nodejs。依赖了如下的包:
"dependencies": {
"html-pdf": "^2.1.0",
"moment": "^2.18.1",
"phantomjs": "^2.1.7"
}
2.设计函数
/**
* Created by saidesun on 17/8/30.
*/
var pdf = require('html-pdf'); // html-pdf
exports.createPDFProtocolFile = function (template, options, reg, filename) {
/**
template: html 模板
options: 配置
reg: 正则匹配规则
filename: 输出pdf文件路径及文件名
*/
// 将所有匹配规则在html模板中匹配一遍
if (reg && Array.isArray(reg)) {
reg.forEach(item => {
template = template.replace(item.relus, item.match);
});
}
pdf.create(template, options).toFile(fi