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:
- Render the Pug template into HTML
- 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(pdfRenderer())
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.
Leave a Reply