Currently I am testing html-pdf module to generate pdfs from html. And I have successfully generated one. But the issue is that the text/data in the html is fixed at the moment.
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.
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? Any help will be greatly appreciated.
Unfortunately, html-pdf
module can't handle the dynamic data. You can take a look at the phantomjs which does the screen capture.
In fact, html-pdf
module uses "phantomjs" at background. However, it uses the small feature of phantomjs.
You can check dynamic-html-pdf
Just follow the steps:
Install using this command npm install dynamic-html-pdf --save
Create html template
Create pdf with below code:
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
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.