Created
June 4, 2018 14:14
-
-
Save hagemann/fd62b6c972353387ed4f8637c36515a9 to your computer and use it in GitHub Desktop.
Example to generate PDF with external image
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@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 withreq.params.slug
.