A node package to convert HTML to PDF, it supports sending in straight HTML and convert to PDF. It also supports sending in template in handlebars format with a data string and convert that to PDF
npm install htmltopdf
It converts raw HTML string data or a stream from a file.
The gist of it is that there are two methods
Both of these methods are what make up this package, the callback is in the classic Node style, basically a function that has two parameters, callback (error, success) which do what they imply, if success then no error, if not success then the error field is populated with the information needed to correctify.
The former method createFromHtml(html, pdfName, callback) takes in an HTML string and the name of the PDF to be created and the previously explained callback.
htmltopdf.createFromHtml("<html><h1>html</h1></html>", "pdfName.pdf", function (err, success) {
... do stuff
});
If you want to read in a file just use the fs module
fs.readFile('file.html', function (err, data) {
htmltopdf.createFromHtml(data, "pdfName.pdf", function (err, success) {
... do stuff
});
});
The latter method createFromTemplateData(html, htmlData, pdfName, callback) uses templates to create the PDF. You send in the template HTML, such as
<html><h1>{{data}}</h1></html>
{{'data':'test'}}
<html><h1>test</h1></html>
htmltopdf.createFromTemplateData("<html><h1>{{data}}</h1></html>", "{{'data':'test'}}", "pdfName.pdf", function (err, success) {
if (success) {
... do stuff
}
});
var htmltopdf = require('./htmltopdf'),
fs = require('fs');
if (process.argv.length > 2) {
var pdfName = process.argv[2];
var html = process.argv[3];
if (pdfName.indexOf('.pdf') > 0) {
var htmlData = process.argv[4];
// If htmlData is valid
if (!!htmlData) {
htmltopdf.createFromTemplateData(html, htmlData, pdfName, function (err, success) {
if (success) {
console.log('Success creating ' + pdfName);
}
else {
console.log('Could not create PDF', err);
}
});
}
else {
htmltopdf.createFromHtml(html, pdfName, function (err, success) {
if (success) {
console.log('Success creating ' + pdfName);
}
else {
console.log('Could not create PDF', err);
}
});
}
}
}