[英]Using html-pdf with dynamic data
Currently I am testing html-pdf module to generate pdfs from html.目前我正在测试html-pdf模块以从 html 生成 pdf。 And I have successfully generated one.
我已经成功生成了一个。 But the issue is that the text/data in the html is fixed at the moment.
但问题是 html 中的文本/数据目前是固定的。
What I am trying to do is have an html form on the front-end which the user fills and then generate a pdf which includes the content the user typed.我想做的是在前端有一个用户填写的html表单,然后生成一个包含用户输入内容的pdf。
What I have done so far:到目前为止我做了什么:
app.post('/pdf',function(req, res) {
pdf.create(html, options).toFile('./businesscard.pdf', function(err, res) {
if (err) return console.log(err);
console.log(res);
});
});
Is this possible using html-pdf?这可能使用html-pdf吗? Any help will be greatly appreciated.
任何帮助将不胜感激。
Unfortunately, html-pdf
module can't handle the dynamic data. 不幸的是,
html-pdf
模块无法处理动态数据。 You can take a look at the phantomjs which does the screen capture. 您可以看一下进行屏幕捕获的phantomjs 。
In fact, html-pdf
module uses "phantomjs" at background. 实际上,
html-pdf
模块在后台使用“ phantomjs”。 However, it uses the small feature of phantomjs. 但是,它使用了phantomjs的小功能。
You can check dynamic-html-pdf您可以查看dynamic-html-pdf
Just follow the steps:只需按照以下步骤操作:
Install using this command npm install dynamic-html-pdf --save
使用此命令
npm install dynamic-html-pdf --save
Create html template创建 html 模板
Create pdf with below code:使用以下代码创建pdf:
var fs = require('fs'); var pdf = require('dynamic-html-pdf'); var html = fs.readFileSync('template.html', 'utf8'); pdf.registerHelper('ifCond', function (v1, v2, options) { if (v1 === v2) { return options.fn(this); } return options.inverse(this); }) var options = { format: "A3", orientation: "portrait", border: "10mm" }; //Your dynamic data var users = [ { name: 'aaa', age: 24, dob: '1/1/1991' }, { name: 'bbb', age: 25, dob: '1/1/1995' }, { name: 'ccc', age: 24, dob: '1/1/1994' } ]; var document = { type: 'buffer', // 'file' or 'buffer' template: html, context: { users: users }, path: "./output.pdf" // it is not required if type is buffer }; pdf.create(document, options) .then(res => { console.log(res) }) .catch(error => { console.error(error) });
I was finding solution for the same and got around one.我正在寻找相同的解决方案并得到了解决方案。
https://medium.com/free-code-camp/how-to-generate-dynamic-pdfs-using-react-and-nodejs-eac9e9cb4dde https://medium.com/free-code-camp/how-to-generate-dynamic-pdfs-using-react-and-nodejs-eac9e9cb4dde
you can checkout this work around done in the blog.您可以在博客中查看这项工作。 He simply called a function that returns an HTML string and he use backticks for dynamic data.
他只是调用了一个返回 HTML 字符串的函数,并使用反引号表示动态数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.