McAPI - HTML to PDF Converter API JavaScript / Node JS

JavaScript / Node sample code to convert HTML and Website content to PDF with the McAPI HTML to PDF Converter REST API service.

Requirements: A free RapidAPI account. Replace YOUR_API_KEY in the snippets below with your RapidAPI key.

All samples below work with the free tier of the API, see the McAPI HTML to PDF API Listing for available plans.

See the overview page for a reference that lists all available parameters and error codes.

Convert an HTML Invoice to PDF in Node JS with request module

Although deprecated, the request module is still in wide use. In the first snippet, we'll convert this HTML invoice to PDF, a typical use case of HTML to PDF conversion. We set the page format to "A4" (the default). With the storeExternal option set to "true", the PDF will be returned as a downloadable URL.

The source code:

// JavaScript
  
const request = require('request');

const options = {
  method: 'POST',
  url: 'https://mcapi-html-2-pdf.p.rapidapi.com/',
  headers: {
    'content-type': 'application/json',
    'x-rapidapi-key': 'YOUR_API_KEY',
    'x-rapidapi-host': 'mcapi-html-2-pdf.p.rapidapi.com',
  },
  body: {
    url: 'https://mcapi.io/html2pdf/templates/invoice.html',
    format: 'A4',
    storeExternal: 'true'
  },
  json: true
};

request(options, function (error, response, body) {
	if (error) throw new Error(error);

	console.log(body);
});

The response will be delivered as a JSON object in body, e.g.:

{
  "service": "McAPI HTML 2 PDF, https://mcapi.io",
  "version": "V1",
  "pdf": "https://...pdf"
}

McAPI HTML 2 PDF API - Converted HTML Invoice as PDF with JavaScript

The returned PDF from the Node JS request, seen here in the macOS Preview. The PDF is fully searchable:

Image of Converted HTML Invoice to PDF JavaScript

Convert HTML to PDF using Node JS with the axios module

A modern, promise based replacement for request is the axios module which is almost 100% source code compatible.

Here's the API call for the same HTML invoice as above with axios:

// JavaScript
  
var axios = require("axios").default;

var options = {
  method: 'POST',
  url: 'https://mcapi-html-2-pdf.p.rapidapi.com/',
  headers: {
    'content-type': 'application/json',
    'x-rapidapi-key': 'YOUR_API_KEY',
    'x-rapidapi-host': 'mcapi-html-2-pdf.p.rapidapi.com',
  },
  data: {
    url: 'https://mcapi.io/html2pdf/templates/invoice.html',
    format: 'A4',
    storeExternal: 'true'
  }
};

axios.request(options).then(function (response) {
	console.log(response.data);
}).catch(function (error) {
	console.error(error);
});

Specifying page formats

The HTML to PDF Converter API contains a built-in list of common paper formats, e.g. "A4" or "letter". To get a list of all formats use the listFormats option, like so:

// JavaScript
  
...

body: {
  listFormats: 'true',
}

...

The API will now return an array of all predefined formats:

{
  formats: ["Letter", "Legal", "Tabloid", "Ledger", "A0", "A2", "A3", "A4", "A5", "A6"]
}

Specifying a predefined format is simple, just use its name in the call:

// JavaScript
  
...

body: {
  url: 'https://mcapi.io/html2pdf/templates/invoice.html',
  format: 'Letter',
  storeExternal: 'true'
}

...

Posting HTML code for conversion to PDF with JavaScript

All previous examples sent URLs for conversion to the API. You can also post HTML code directly to the API. Use the html parameter for this. We first load the HTML code from a file, then escape it so that it can be put into a JSON block:

// JavaScript

const fs = require('fs');

let data = fs.readFileSync('templates/invoice_1.html');
let html = JSON.stringify(data.toString('ascii'));  

Then we set the parameters:

// JavaScript

...

body: {
  "html": html,
  "format": "A4",
  "storeExternal": "true"
}'

...

Note that all references in the HTML string must be absolute, e.g. something like this will not resolve:

<img src="../templates/logo.png"/>

All references must be absolute and point to valid web locations, example:

<img src="https://mcapi.io/html2pdf/templates/logo.png"/>

Make sure to see the discussion in the API overview on this.

With your call you can also specify headers and footers to be put on each page of the generated PDF. The overview has more on this and provides some examples.

Cookie consent banners and ad blocking

If so desired, the API can also automatically click the "Accept" button on GDPR cookie consent banners (Note that this feature is currently experimental, discussion.)

Consider the CNBC website which we convert to a PDF with this snippet:

// JavaScript
  
...

body: {
  url: 'https://cnbc.com',
  format: 'A4',
  background: 'true',
  orientation: 1,
  storeExternal: 'true'
}

...

The site displays a very large cookie consent banner. Screenshot from the captured PDF (link to PDF):

Website HTML to PDF Conversion with Cookie Banner

Set the cookie option to "true" like so:

// JavaScript
  
...

body: {
  url: 'https://cnbc.com',
  format: 'A4',
  cookie: 'true',
  background: 'true',
  orientation: 1,
  storeExternal: 'true'
}

...

The site without the banner but with ads instead (link to PDF):

Website HTML to PDF Conversion with Ad.png

Blocking ads in PDFs

While it can be useful to convert websites with all ads (for example to document ad placement or to check ad rotation), in many cases you want the PDFs without any ads. The API comes with a built-in ad blocker, activate it like so:

// JavaScript
  
...

body: {
  url: 'https://cnbc.com',
  format: 'A4',
  cookie: 'true',
  adblock: 'true',
  background: 'true',
  orientation: 1,
  storeExternal: 'true'
}

...

The website now without cookie warning and without ads (link to PDF):

Website HTML to PDF Conversion no Cookies no Ads

For the PDF of the CNBC website we had set the orientation to "1" (for landscape) and the background option to "true". This is a sensible option for converting websites to PDF because they often have inverted text and similar styling. Here's the same site without background elements (the default):

Website HTML to PDF Conversion Transparent Background

As a rule of thumb, leave background at "false" if you convert documents like invoices, package lists, time sheets and the like, set it to "true" for websites.

The header-parameter - writing PDFs to a file (JavaScript)

With the storeExternal option set to "false", the PDF is returned immediately as a base64 encoded string. Per default, this string is preceded by a header that describes the media type (or MIME) of the string.

Sample body block:

// JavaScript

...

body: {
  url: 'https://mcapi.io/html2pdf/templates/invoice.html',
  format: 'A4',
  storeExternal: 'false'
}

...

The result will look like this:

{
  "service": "McAPI HTML 2 PDF, https://mcapi.io",
  "version": "V1",
  "pdf": "data:application/pdf;base64,JVBERi0 ... JUVPRg=="
}

You can now directly set the "pdf"-string as the data property of an object tag, like so:

// JavaScript

...

if(result.statusCode == 200){
  let pdfData = body.pdf;
  console.log('<object data="' + pdfData + '"/>');
}
else{
  // error handling
}

...

The MIME header will make sure that the data is interpreted as a PDF by the browser (Note that not all browsers support the embedding of PDF files with the object tag, see this discussion on Stackoverflow.)

However, when writing the PDF data to a file, including the header would result in an invalid PDF document. To create a PDF without the header, set the header-parameter to "false", like so:

// JavaScript

...

body: {
  url: 'https://mcapi.io/html2pdf/templates/invoice.html',
  format: 'A4',
  storeExternal: 'false',
  header: 'false'
}

...

The returned PDF data without header:

{
  "service": "McAPI HTML 2 PDF, https://mcapi.io",
  "version": "V1",
  "pdf": "JVBERi0 ... JUVPRg=="
}

Now, all we have to do is decode the base64 string using a buffer and then write the PDF to a file, shown here as a complete NodeJS program:

// JavaScript

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

const options = {
  method: 'POST',
  url: 'https://mcapi-html-2-pdf.p.rapidapi.com/',
  headers: {
    'content-type': 'application/json',
    'x-rapidapi-key': 'YOUR_API_KEY',
    'x-rapidapi-host': 'mcapi-html-2-pdf.p.rapidapi.com',
  },
  body: {
    url: 'https://mcapi.io/html2pdf/templates/invoice.html',
    format: 'A4',
    storeExternal: 'false',
    header: 'false'
  },
  json: true
};

request(options, function (error, response, body) {
  if (error) throw new Error(error);
  if(response.statusCode == 200){
    let pdfData = body.pdf;
    var buffer = Buffer.from(pdfData, 'base64');
    
    fs.writeFile('document.pdf', buffer, err => {
      if (err) {
        // error handling
      }
    })
  }
  else{
    // error handling
  }
});


Back to McAPI HTML to PDF API main page.