Security News
Research
Data Theft Repackaged: A Case Study in Malicious Wrapper Packages on npm
The Socket Research Team breaks down a malicious wrapper package that uses obfuscation to harvest credentials and exfiltrate sensitive data.
The html-pdf npm package allows you to convert HTML content into PDF documents. It is useful for generating PDFs from web pages, HTML strings, or even local HTML files. The package provides a simple API to customize the PDF output, including options for page size, margins, headers, footers, and more.
Convert HTML String to PDF
This feature allows you to convert an HTML string directly into a PDF file. The code sample demonstrates how to create a simple PDF from an HTML string and save it to a file.
const pdf = require('html-pdf');
const html = '<h1>Hello, World!</h1>';
pdf.create(html).toFile('./output.pdf', function(err, res) {
if (err) return console.log(err);
console.log(res); // { filename: '/path/to/output.pdf' }
});
Convert HTML File to PDF
This feature allows you to convert an HTML file into a PDF. The code sample demonstrates how to read an HTML file from the filesystem and convert it into a PDF file.
const pdf = require('html-pdf');
const fs = require('fs');
const html = fs.readFileSync('./template.html', 'utf8');
pdf.create(html).toFile('./output.pdf', function(err, res) {
if (err) return console.log(err);
console.log(res); // { filename: '/path/to/output.pdf' }
});
Custom PDF Options
This feature allows you to customize the PDF output by specifying options such as page format, orientation, and margins. The code sample demonstrates how to create a PDF with custom options.
const pdf = require('html-pdf');
const html = '<h1>Hello, World!</h1>';
const options = { format: 'Letter', orientation: 'portrait', border: '1in' };
pdf.create(html, options).toFile('./output.pdf', function(err, res) {
if (err) return console.log(err);
console.log(res); // { filename: '/path/to/output.pdf' }
});
Add Headers and Footers
This feature allows you to add headers and footers to the PDF. The code sample demonstrates how to include custom header and footer content in the PDF output.
const pdf = require('html-pdf');
const html = '<h1>Hello, World!</h1>';
const options = {
header: { height: '45mm', contents: '<div style="text-align: center;">Author: John Doe</div>' },
footer: { height: '28mm', contents: '<span style="color: #444;">{{page}}</span>/<span>{{pages}}</span>' }
};
pdf.create(html, options).toFile('./output.pdf', function(err, res) {
if (err) return console.log(err);
console.log(res); // { filename: '/path/to/output.pdf' }
});
Puppeteer is a Node library which provides a high-level API to control Chrome or Chromium over the DevTools Protocol. It can be used to generate PDFs from web pages. Compared to html-pdf, Puppeteer offers more control over the browser environment and can handle more complex rendering tasks.
PDFKit is a JavaScript library for generating PDFs programmatically. Unlike html-pdf, which converts HTML to PDF, PDFKit allows you to create PDFs from scratch using JavaScript. It provides a rich API for drawing text, images, and shapes directly into the PDF.
wkhtmltopdf is a command-line tool to render HTML into PDF using Webkit. It can be used in Node.js applications via various wrappers. Compared to html-pdf, wkhtmltopdf is a standalone tool that can be integrated into different environments and offers extensive customization options.
Example Business Card
-> and its Source file
Have a look at the releases page: https://github.com/marcbachmann/node-html-pdf/releases
Install the html-pdf utility via npm:
$ npm install -g html-pdf
$ html-pdf test/businesscard.html businesscard.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' }
});
var pdf = require('html-pdf');
pdf.create(html).toFile([filepath, ]function(err, res){
console.log(res.filename);
});
pdf.create(html).toStream(function(err, stream){
stream.pipe(fs.createWriteStream('./foo.pdf'));
});
pdf.create(html).toBuffer(function(err, buffer){
console.log('This is a buffer:', Buffer.isBuffer(buffer));
});
// for backwards compatibility
// alias to pdf.create(html[, options]).toBuffer(callback)
pdf.create(html [, options], function(err, buffer){});
html-pdf
can read the header or footer either out of the footer
and header
config object or out of the html source. You can either set a default header & footer or overwrite that by appending a page number (1 based index) to the id="pageHeader"
attribute of a html tag.
You can use any combination of those tags. The library tries to find any element, that contains the pageHeader
or pageFooter
id prefix.
<div id="pageHeader">Default header</div>
<div id="pageHeader-first">Header on first page</div>
<div id="pageHeader-2">Header on second page</div>
<div id="pageHeader-3">Header on third page</div>
<div id="pageHeader-last">Header on last page</div>
...
<div id="pageFooter">Default footer</div>
<div id="pageFooter-first">Footer on first page</div>
<div id="pageFooter-2">Footer on second page</div>
<div id="pageFooter-last">Footer on last page</div>
config = {
// Export options
"directory": "/tmp", // The directory the file gets written into if not using .toFile(filename, callback). default: '/tmp'
// Papersize Options: http://phantomjs.org/api/webpage/property/paper-size.html
"height": "10.5in", // allowed units: mm, cm, in, px
"width": "8in", // allowed units: mm, cm, in, px
- or -
"format": "Letter", // allowed units: A3, A4, A5, Legal, Letter, Tabloid
"orientation": "portrait", // portrait or landscape
// Page options
"border": "0", // default is 0, units: mm, cm, in, px
- or -
"border": {
"top": "2in", // default is 0, units: mm, cm, in, px
"right": "1in",
"bottom": "2in",
"left": "1.5in"
},
paginationOffset: 1, // Override the initial pagination number
"header": {
"height": "45mm",
"contents": '<div style="text-align: center;">Author: Marc Bachmann</div>'
},
"footer": {
"height": "28mm",
"contents": {
first: 'Cover page',
2: 'Second page', // Any page number is working. 1-based index
default: '<span style="color: #444;">{{page}}</span>/<span>{{pages}}</span>', // fallback value
last: 'Last Page'
}
},
// Rendering options
"base": "file:///home/www/your-asset-path/", // Base path that's used to load files (images, css, js) when they aren't referenced using a host
// Zooming option, can be used to scale images if `options.type` is not pdf
"zoomFactor": "1", // default is 1
// File options
"type": "pdf", // allowed file types: png, jpeg, pdf
"quality": "75", // only used for types png & jpeg
// Script options
"phantomPath": "./node_modules/phantomjs/bin/phantomjs", // PhantomJS binary which should get downloaded automatically
"phantomArgs": [], // array of strings used as phantomjs args e.g. ["--ignore-ssl-errors=yes"]
"localUrlAccess": false, // Prevent local file:// access by passing '--local-url-access=false' to phantomjs
// For security reasons you should keep the default value if you render arbritary html/js.
"script": '/url', // Absolute path to a custom phantomjs script, use the file in lib/scripts as example
"timeout": 30000, // Timeout that will cancel phantomjs, in milliseconds
// Time we should wait after window load
// accepted values are 'manual', some delay in milliseconds or undefined to wait for a render event
"renderDelay": 1000,
// HTTP Headers that are used for requests
"httpHeaders": {
// e.g.
"Authorization": "Bearer ACEFAD8C-4B4D-4042-AB30-6C735F5BAC8B"
},
// To run Node application as Windows service
"childProcessOptions": {
"detached": true
}
// HTTP Cookies that are used for requests
"httpCookies": [
// e.g.
{
"name": "Valid-Cookie-Name", // required
"value": "Valid-Cookie-Value", // required
"domain": "localhost",
"path": "/foo", // required
"httponly": true,
"secure": false,
"expires": (new Date()).getTime() + (1000 * 60 * 60) // e.g. expires in 1 hour
}
]
}
The full options object gets converted to JSON and will get passed to the phantomjs script as third argument.
There are more options concerning the paperSize, header & footer options inside the phantomjs script.
FAQs
HTML to PDF converter that uses phantomjs
We found that html-pdf demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Research
The Socket Research Team breaks down a malicious wrapper package that uses obfuscation to harvest credentials and exfiltrate sensitive data.
Research
Security News
Attackers used a malicious npm package typosquatting a popular ESLint plugin to steal sensitive data, execute commands, and exploit developer systems.
Security News
The Ultralytics' PyPI Package was compromised four times in one weekend through GitHub Actions cache poisoning and failure to rotate previously compromised API tokens.