Skip to content

Instantly share code, notes, and snippets.

Created June 4, 2018 14:14
Show Gist options
  • Save hagemann/fd62b6c972353387ed4f8637c36515a9 to your computer and use it in GitHub Desktop.
Save hagemann/fd62b6c972353387ed4f8637c36515a9 to your computer and use it in GitHub Desktop.
Example to generate PDF with external image
const Printer = require('pdfmake')
const axios = require('axios')
const path = require('path')
module.exports.pdf = async (req, res, next) => {
var printer = new Printer({
Roboto: {
normal: path.resolve('src', 'fonts', 'Roboto.ttf'),
bold: path.resolve('src', 'fonts', 'Roboto-Bold.ttf'),
try {
var result = await axios.get('', {
responseType: 'arraybuffer'
} catch(err) {
return next(err.message)
var image = new Buffer(, 'base64')
var doc = printer.createPdfKitDocument({
info: {
title: 'PDF with External Image',
author: 'Matt Hagemann',
subject: 'PDF with External Image',
content: [{
image: image,
width: 595, // Full A4 size width.
absolutePosition: { x: 0, y: 0 }
defaultStyle: {
fontSize: 11,
font: 'Roboto', // The font name was defined above.
lineHeight: 1.2,
res.setHeader('Content-type', 'application/pdf')
res.setHeader('Content-disposition', 'inline; filename="Example.pdf"')
Copy link

@jeppe-sohn Sure. I really suggest to work through the Getting Started guides offered on their website if you want to learn Node or Express. Your index.js could look something like this (untested).

const express = require('express')
const app = express()
const port = 3000
const pdfController = require('./pdf') // Include the pdf.js of this Gist. No need for .js suffix.

app.get('/pdf', pdfController.pdf) // “.pdf” because it’s the exported module “modules.exports.pdf”

app.listen(port, () => console.log(`Example app listening on port ${ port }!`))

When the app starts successfully, the PDF can be loaded on your browser at http://localhost:3000/pdf

Copy link

Thanks a bunch!
This will get me started :)
Best Regards Jeppe

Copy link

gecko9 commented Sep 5, 2020

Great example, thank you. I need to serve up different pdf's depending on the given url (example '/pdf1' or '/pdf2' etc). There could be alot of pdf's so I'm thinking the source for each could be located in it's own pdfXX.js file. But so far I can't see how to conditionally require the pdfController depending on the url.
I would really appreciate any hints!

Copy link

hagemann commented Sep 5, 2020

@gecko9 This has to happen on the router level. You serve routes with dynamic slugs (e.g. /:slug) and read that slug inside the controller with req.params.slug.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment