Use HTML and puppeteer to create PDFs in Node.js

Florian Streise
2 min readSep 29, 2019

--

Every now and then you as a developer need to create PDFs on the server. An example could be an invoice that you want to send to a customer. With Node.js there are not a lot of good libraries out there so in this article, I want to show you a simple way to easily create PDFs from HTML with puppeteer!

Puppeteer is a Node library that provides a high-level API to control headless Chrome or Chromium over the DevTools Protocol. This means that you can tell Chrome via JavaScript to open a new tab, navigate to an url, fill a form or interact with websites. In this article, we will use puppeteer to render a HTML file and create a PDF.

First of all, you will need to create a new project and install puppeteer.

create project and install dependencies

Now you need a template for our PDF. I borrowed a template from this Github repository.

Now that you have everything installed and your template in place, it’s time to create the PDF! For this, you need to tell puppeteer to launch a new chrome instance. Then you will open a new page and set the content to your HTML. After that, you can either create a Buffer of the PDF file or simply save it to disk.

Important: For puppeteer.pdf to work, you have to set headless to true, otherwise puppeteer will not be capable to create the PDF. If you set headless to false you can inspect the HTML you created.

Et voila, this is our fancy invoice as a pdf file:

--

--