Skip to content

Instantly share code, notes, and snippets.

@hagemann
Created June 4, 2018 14:14
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • 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('http://via.placeholder.com/350x150', {
responseType: 'arraybuffer'
})
} catch(err) {
return next(err.message)
}
var image = new Buffer(result.data, '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,
}
})
doc.end()
res.setHeader('Content-type', 'application/pdf')
res.setHeader('Content-disposition', 'inline; filename="Example.pdf"')
doc.pipe(res)
}
@hagemann
Copy link
Author

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