How to convert HMTL to PDF in Node.JS

It is quite easy to utilize HTML to PDF API in your Node.JS applications. While there are many options, we suggest using request module to communicate with the API.

Prerequisites

Install request module from NPM

npm install request

Obtain your access token

Please visit tokens page and copy your access token. We will refer to the token as TOKEN in this guide.

Usage

Convert a URL to PDF and save to disk

This snippet uses HTML to PDF API to generate a PDF and stream back the resulting file. You need to specify encoding: null to ensure that the resulting data is passed as a Buffer object. After receiving the response, we write the file to out.pdf in this sample but it’s up to you to use it as you wish.

var request = require('request');
var fs = require('fs');

request({
  url: 'https://restpack.io/api/html2pdf/v3/convert',
  qs: {
    access_token: 'TOKEN',
    url: 'http://google.com'
  },
  encoding: null // In order to receive a Buffer as response
}, function(err, resp, body) {
  if (err) {
    console.error(err);
    process.exit(-1);
  }

  fs.writeFile('out.pdf', body, function() {
    console.log("PDF Saved.");
  })
})

Convert an HTML string to PDF

Here, instead of sending a url querystring parameter, we are POSTing a json document with html_data string. It can contain complex html, css, inline JS etc.

var request = require('request');
var fs = require('fs');

request({
  url: 'https://restpack.io/api/html2pdf/v3/convert',
  method: 'POST',
  qs: {
    access_token: 'TOKEN',
  },
  json: {
    html_data: '<strong>Bold text here</strong> and regular here..'
  },
  encoding: null // In order to receive a Buffer as response
}, function(err, resp, body) {
  if (err) {
    console.error(err);
    process.exit(-1);
  }

  // use body
})

Obtain a reusable URL for converted PDF

If you don’t need to store / process the output PDF, you can use our publicly accessible CDN servers to serve the PDF file.

var request = require('request');
var fs = require('fs');

request({
  url: 'https://restpack.io/api/html2pdf/v3/convert',
  qs: {
    access_token: 'TOKEN',
    url: 'http://google.com',
    json: true
  }
}, function(err, resp, body) {
  if (err) {
    console.error(err);
    process.exit(-1);
  }

  console.log("PDF Url: " + body.mediaLink)
})

For detailed usage instructions, please check the Documentation page.