How to convert HTML to PDF in Node.js

PDFShift provides a Node.js package available for free at https://github.com/pdfshift/pdfshift-node

Documentation

See the full documentation on PDFShift's documentation.

Installation

You should not require this code directly. Instead, just run:

npm install --save pdfshift

Requirements

Usage

This library needs to be configured with your api_key received when creating an account.
Setting it is easy as:

const pdfshift = require('pdfshift')('your_api_key');
const fs = require('fs');

pdfshift.convert('https://www.example.com').then(function (binary_file) {
    fs.writeFile('result.pdf', binary_file, "binary", function () {})
}).catch(function({message, code, response, errors = null}) {})

We also highly recommend checking for errors after the conversion is made, before processing the document, in order to avoid issues later on.
This can be easily handled with requests by doing the following:

const pdfshift = require('pdfshift')('your_api_key');
const fs = require('fs');

pdfshift.convert('https://www.example.com').then(function (binary_file) {
    fs.writeFile('result.pdf', binary_file, "binary", function () {})
}).catch(function({message, code, response, errors = null}) {
    // Handle any error that might have occured here.
})

The sandbox parameter allows you to do unlimited conversion, but will add a watermark on top of the generated document.
No credits are deduced from your account when the sandbox mode is on.

const pdfshift = require('pdfshift')('your_api_key');
const fs = require('fs');

// For converting directly
pdfshift.convert('https://www.example.com', {sandbox: true}).then(function (binary_file) {
    fs.writeFile('result.pdf', binary_file, "binary", function () {})
}).catch(function({message, code, response, errors = null}) {})

// Or when preparing a more advanced call:
pdfshift.prepare('https://httpbin.org/headers', {sandbox: true})
    .setHTTPHeaders({
        'X-Original-Header': 'Awesome value'
    })
    .addHTTPHeader('user-agent', 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0') // Also works like this
    .convert()
    .then(function (binary_file) {
        fs.writeFile('result.pdf', binary_file, "binary", function () {})
    })
    .catch(function({message, code, response, errors = null}) {})

With an URL

Converting an URL with PDFShift is really easy. All you have to do is send a POST request with the source parameter set to the URL, like the following:

const pdfshift = require('pdfshift')('your_api_key');
const fs = require('fs');

pdfshift.convert('https://www.example.com').then(function (binary_file) {
    fs.writeFile('result.pdf', binary_file, "binary", function () {})
}).catch(function({message, code, response, errors = null}) {})

With inline HTML data:

To convert a raw HTML data with PDFShift, simply send the raw string in the source parameter:

const pdfshift = require('pdfshift')('your_api_key');
const fs = require('fs');

let data = fs.readFileSync('invoice.html', 'utf8');

pdfshift.convert(data).then(function (binary_file) {
    fs.writeFile('result.pdf', binary_file, "binary", function () {})
}).catch(function({message, code, response, errors = null}) {})

Save the file to Amazon S3 and get an URL instead

By passing the filename parameter to your request, you will receive a JSON response instead of the binary PDF, with a url key that contains the path to the file stored on Amazon S3.
All files stored on Amazon S3 are kept for two days, then automatically deleted.

const pdfshift = require('pdfshift')('your_api_key');
const fs = require('fs');

pdfshift.convert('https://www.example.com', {filename: 'result.pdf'}).then(function (body) {
    let json = JSON.parse(body);
    // The URL is on 
    console.log(json.url);
}).catch(function({message, code, response, errors = null}) {})

Custom HTTP Headers

You can pass custom HTTP headers, allowing you to adapt to the server handling your source. This can be a custom identification header, changing the language, or anything else.

const pdfshift = require('pdfshift')('your_api_key');
const fs = require('fs');

// We use .prepare() instead of .convert to easily handle advanced configuration
pdfshift.prepare('https://httpbin.org/headers')
    .setHTTPHeaders({
        'X-Original-Header': 'Awesome value'
    })
    .addHTTPHeader('user-agent', 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0') // Also works like this
    .convert()
    .then(function (binary_file) {
        fs.writeFile('result.pdf', binary_file, "binary", function () {})
    })
    .catch(function({message, code, response, errors = null}) {})

Accessing secured pages

If your source requires a BASIC AUTH mechanism, you can either use the custom headers part or use the auth parameter from the API that behaves the same.

const pdfshift = require('pdfshift')('your_api_key');
const fs = require('fs');

// We use .prepare() instead of .convert to easily handle advanced configuration
pdfshift.prepare('https://httpbin.org/basic-auth/user/passwd')
    .auth('user', 'passwd')
    .convert()
    .then(function (binary_file) {
        fs.writeFile('result.pdf', binary_file, "binary", function () {})
    })
    .catch(function({message, code, response, errors = null}) {})

Using cookies

Cookies might help you access unauthorized areas that aren't restricted by a simple Basic Auth mechanism. You can define as many cookies as you want.

const pdfshift = require('pdfshift')('your_api_key');
const fs = require('fs');

// We use .prepare() instead of .convert to easily handle advanced configuration
pdfshift.prepare('https://httpbin.org/cookies')
    .addCookie({name: 'session', value: '4cb496a8-a3eb-4a7e-a704-f993cb6a4dac'})
    .convert()
    .then(function (binary_file) {
        fs.writeFile('result.pdf', binary_file, "binary", function () {})
    })
    .catch(function({message, code, response, errors = null}) {})

Loading CSS from an URL:

By passing a css parameter, you will be able to modify the page with your CSS.
This allows you to customize the rendering of the page.

You can also call multiple CSS by calling a root CSS (like "print.css" in that case) that will call @import in it for each CSS files.

const pdfshift = require('pdfshift')('your_api_key');
const fs = require('fs');

pdfshift.convert('https://www.example.com', {css: 'https://www.example.com/public/css/print.css'}).then(function (binary_file) {
    fs.writeFile('result.pdf', binary_file, "binary", function () {})
}).catch(function({message, code, response, errors = null}) {})

Loading CSS from a string:

Like for the source parameter, you can pass a raw set of CSS rules to the css parameter and they will be injected to the loaded document.

const pdfshift = require('pdfshift')('your_api_key');
const fs = require('fs');

pdfshift.convert('https://www.example.com', {css: 'a {text-decoration: underline; color: blue}'}).then(function (binary_file) {
    fs.writeFile('result.pdf', binary_file, "binary", function () {})
}).catch(function({message, code, response, errors = null}) {})

Adding Watermark

Some documents that you share need a watermark to clearly identify your brand. That's easy with PDFShift:

const pdfshift = require('pdfshift')('your_api_key');
const fs = require('fs');

// We use .prepare() instead of .convert to easily handle advanced configuration
pdfshift.prepare('https://www.example.com')
    .watermark({
        image: 'https://pdfshift.io/static/img/logo.png',
        offset_x: 50,
        offset_y: '100px',
        rotate: 45
    })
    .convert()
    .then(function (binary_file) {
        fs.writeFile('result.pdf', binary_file, "binary", function () {})
    })
    .catch(function({message, code, response, errors = null}) {})

You can add some custom header or footer to your generated document. These are often used to indicate the current page, or show the logo of your company on every page.

Note that the header and footer are not related to the body. For this reason, the CSS in your body doesn't apply to your header/footer.
By default, the font-size will be really small. You will have to set it manually, like in the following example:

const pdfshift = require('pdfshift')('your_api_key');
const fs = require('fs');

// We use .prepare() instead of .convert to easily handle advanced configuration
pdfshift.prepare('https://www.example.com')
    .footer({source: '<div>Page  of </div>', spacing: '50px'})
    .convert()
    .then(function (binary_file) {
        fs.writeFile('result.pdf', binary_file, "binary", function () {})
    })
    .catch(function({message, code, response, errors = null}) {})

Protecting the generated PDF

Protecting your document is easy with PDFShift. You can specify a password for the user and for the owner.
(The owner will have full rights access while the user will have limited access based on your choice).

Please keep in mind that some PDF reader doesn't respect the rights as long as the user is authenticated.
This means that if you set an empty password for the user, with no rights to print or copy, some PDF reader will ignore this and still allow printing and copying.

This is outside of our capabilities here at PDFShift as we can't enforce a reader to respect PDF's standard.

const pdfshift = require('pdfshift')('your_api_key');
const fs = require('fs');

// We use .prepare() instead of .convert to easily handle advanced configuration
pdfshift.prepare('https://www.example.com')
    .protect({
        user_password: 'user',
        owner_password: 'owner',
        no_print: true
    })
    .convert()
    .then(function (binary_file) {
        fs.writeFile('result.pdf', binary_file, "binary", function () {})
    })
    .catch(function({message, code, response, errors = null}) {})

(Read our API documentation for more, in depth, details.)