htmltopdf

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

Downloads in past

Stats

StarsIssuesVersionUpdatedCreatedSize
htmltopdf
1000.0.86 years ago7 years agoMinified + gzip package size for htmltopdf in KB

Readme

HTML TO PDF
author: Ólafur Aron Jóhannsson
email: olafur@johannsson.co
website: http://olafurjohannsson.com
Convert HTML sites to PDF with this simple package. https://www.npmjs.com/package/htmltopdf npm install htmltopdf

HTML to PDF converter.

It converts raw HTML string data or a stream from a file.

The gist of it is that there are two methods

  • createFromHtml (html, pdfName, callback)
  • createFromTemplateData (html, htmlData, pdfName, callback)

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.

Usage for createFromHtml

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
});
});

Usage for createFromTemplateData

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>
where data is a JS object
{{'data':'test'}}
The output would be
<html><h1>test</h1></html>

Example:

htmltopdf.createFromTemplateData("<html><h1>{{data}}</h1></html>", "{{'data':'test'}}", "pdfName.pdf", function (err, success) {
if (success) {
... do stuff
}
});

Example using fs module

See test.js for examples

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);
}
});
}
}
}