Created
April 19, 2018 15:14
-
-
Save mozfet/1fcaf22e9351a08b33e1dcf88ff2126d to your computer and use it in GitHub Desktop.
Meteor Server Side PDF Generation
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
import PdfMake from 'pdfmake'; | |
import fonts from 'pdfmake/build/vfs_fonts'; | |
import streamBuffers from 'stream-buffers'; | |
// use picker for meteor server side routes | |
Picker.route('/pdf', function(params, req, res, next) { | |
// define the content of the pdf document | |
const documentDefinition = {content: 'Hello World!'}; | |
// define embedded fonts to embed in the pdf document | |
const fontDescriptors = { | |
Roboto: { | |
normal: new Buffer(fonts.pdfMake.vfs['Roboto-Regular.ttf'], 'base64'), | |
bold: new Buffer(fonts.pdfMake.vfs['Roboto-Medium.ttf'], 'base64'), | |
italics: new Buffer(fonts.pdfMake.vfs['Roboto-Italic.ttf'], 'base64'), | |
bolditalics: new Buffer(fonts.pdfMake.vfs['Roboto-MediumItalic.ttf'], 'base64') | |
} | |
}; | |
// setup pdf with document definition for streaming | |
const pdfMake = new PdfMake(fontDescriptors); | |
const pdfDoc = pdfMake.createPdfKitDocument(documentDefinition); | |
// setup writeable stream buffer | |
const streamBuffer = new streamBuffers.WritableStreamBuffer(); | |
// when doc is done streaming | |
pdfDoc.on('end', function () { | |
// get buffer as binary string | |
const pdfBinary = streamBuffer.getContentsAsString('binary'); | |
// write the binary response to the client | |
res.writeHead(200, { | |
'Content-Type': 'application/pdf', | |
'Content-Disposition': 'attachment; filename=doc.pdf' | |
}); | |
res.end(pdfBinary); | |
}); | |
// pipe doc into stream buffer and end the pdf document stream | |
pdfDoc.pipe(streamBuffer); | |
pdfDoc.end(); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment