node html-pdf code example

Example 1: nodejs create pdf

$ npm install pdfkit

const PDFDocument = require('pdfkit');
const fs = require('fs');

var pdfDoc = new PDFDocument;
pdfDoc.pipe(fs.createWriteStream('SampleDocument.pdf'));

pdfDoc.text("From Mon-Sat we will have a 10% discount on selected items!", 150, 150);
pdfDoc
    .fillColor('red')
    .fontSize(17)
    .text("20%", 305, 150);

pdfDoc.end();

Example 2: node js create pdf from html

The problem with using PDF converter libraries available on NPM like pdfkit is that, you gonna have to recreate the page structures again in your html templates to get the desired output.

One of the best approach to rendering html and convert to pdf is by using Puppeteer on NodeJs. 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 screenshots and PDFs of html pages in your case.