Serve PDF documents from templates in Express

There are a number of ways to generate PDF documents in Node. You could manually construct it step-by-step with PDFKit. You could generate it from one of many HTML-to-PDF conversion libraries. If you are already using Pug templates in your app then it would be nice to be able to generate the PDFs from pug.

This is possible in two steps:

  1. Render the Pug template into HTML
  2. Use PhantomJS to render the HTML into PDF

Inspired by and leaning on some excellent NPM modules

I created express-template-to-pdf

Install it, add it to express, and now serving up PDF documents from Pug templates in your express routes is easy

const pdfRenderer = require('@ministryofjustice/express-template-to-pdf')

app.set('views', path.join(__dirname, 'views'))
app.set('view engine', 'pug')


app.use('/pdf', (req, res) => {
  res.renderPDF('helloWorld', { message: 'Hello World!' });

With options to configure the downloaded file name, page margins, and use CSS, serving up PDFs couldn’t be easier.

My colleague Steven joined in and made a few brilliantly simple tweaks, and now you can use the same module to serve PDF generated from whatever type of templates you are using in your express view engine. Not just Pug, but Nunjucks or Mustache or whatever else you fancy.

Posted in Node, Uncategorized

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

<span>%d</span> bloggers like this: