Skip to content

olafurjohannsson/htmltopdf

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

43 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation

HTML TO PDF

author: Ólafur Aron Jóhannsson
email: [email protected]
website: https://www.olafuraron.is

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

}

About

HTML to PDF with this simple package.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published