如何使用`html-pdf`module将html转换为node.js中的pdf

我使用html-pdf模块生成发票。
当我传递网页本地地址,即存储在文件夹中时,我能够生成pdf。
但我的要求是打API,然后生成PDF文件。

我可以使用html-pdf模块做到这一点,或者有其他的模块可以做到这一点?

 var fs = require('fs'); var pdf = require('html-pdf'); var html = fs.readFileSync('./test/businesscard.html', 'utf8'); var options = { format: 'Letter' }; pdf.create(html, options).toFile('./businesscard.pdf', function(err, res) { if (err) return console.log(err); console.log(res); // { filename: '/app/businesscard.pdf' } }); 

请帮忙。

如果我正确阅读这个,你想从HTML文件生成一个PDF,然后将其返回到浏览器/客户端?

这应该做到这一点:

 var fs = require('fs'); var bodyParser = require('body-parser'); var pdf = require('html-pdf'); app.post('/product/invoice', function (req, res) { var htmlPath = req.body.htmlPath; if (!htmlPath){ res.status(400).send("Missing 'htmlPath'"); return; } var html = fs.readFileSync(htmlPath, 'utf8'); // you may want to change this path dynamically if you also wish to keep the generated PDFs var pdfFilePath = './businesscard.pdf'; var options = { format: 'Letter' }; pdf.create(html, options).toFile(pdfFilePath, function(err, res2) { if (err){ console.log(err); res.status(500).send("Some kind of error..."); return; } fs.readFile(pdfFilePath , function (err,data){ res.contentType("application/pdf"); res.send(data); }); }); }); 

您需要使用htmlPath作为参数(这将从您的初始示例中./test/businesscard.html)POST到此端点 – 确保这是正确的URL编码。