Generating PDF document from HTML in NodeJS

If you are wondering how to convert HTML to PDF in NodeJS, then look no further. We'll show you how.

Headless Chrome is the best way to convert raw HTML to PDF. Nothing can render HTML better than a browser and nothing beats Chromium when it comes to rendering HTML. Puppeteer is a wrapper written in NodeJS that makes it very easy to interact with headless Chrome.
const puppeteer = require('puppeteer');

(async () => {
  const browser = await puppeteer.launch();
  const page = await browser.newPage();

  await page.setContent('<html> <body> <h1> Hello World! </h1> </body> </html>', {
    waitUntil: 'networkidle2',
  });
  await page.pdf({ path: 'output.pdf' });

  await browser.close();
})();
Puppeteer comes with its own version of Chromium. It is advisable that you run Puppeteer and headless Chrome on a separate server so it doesn't affect your core application. If you do not want to worry about setting up separate PDF generation server and maintaing it, then you can use our API which is bulilt on top of Puppeteer.

We at PDFMark have done the hard work of managing the headless Chrome and wrapped it into an easy to use REST API so you can simply call the API from your NodeJS application and pass in the HTML or a URL and get it converted to a PDF document. PDFMark will even upload it to cloud and give you a CDN link so you can simply serve that link to your end users without having to worry about saving the document yourself.

Following is the code for calling the PDFMark HTML to PDF REST API in NodeJS
var unirest = require('unirest');
var req = unirest('POST', 'https://api.pdfmark.com/pdf')
  .headers({
    'key': 'YOUR_API_KEY',
    'Content-Type': 'application/json'
  })
  .send(JSON.stringify({
    "html": "<html> <body> <h1> Hello World! </h1> </body> </html>"
  }))
  .end(function (res) {
    if (res.error) throw new Error(res.error);
    console.log(res.raw_body);
  });

Try out PDFMark API with your own HTML or URL

HTML
URL
JSON
   Preview    Try <qr>http://example.com</qr>

Sign up for PDFMark and get your API key. You can start converting your HTML to PDF in next one minute.

Convert HTML to PDF in your favourite programming language. Click on the icon below to view the code

HTML to PDF in C#

HTML to PDF in Php

HTML to PDF in Python

HTML to PDF in Go


HTML to PDF in NodeJS

HTML to PDF in Java

HTML to PDF in VB.Net

HTML to PDF in Ruby