-
-
Save hagemann/fd62b6c972353387ed4f8637c36515a9 to your computer and use it in GitHub Desktop.
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) | |
} |
@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
Thanks a bunch!
This will get me started :)
Best Regards Jeppe
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!
@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
.
Hey
I am new to node so i was wandering if you could give an example of how to use/invoke this from a basic express website?
Thanks in advance