Skip to content

Instantly share code, notes, and snippets.

@mozfet
Created April 19, 2018 15:14
Show Gist options
  • Save mozfet/1fcaf22e9351a08b33e1dcf88ff2126d to your computer and use it in GitHub Desktop.
Save mozfet/1fcaf22e9351a08b33e1dcf88ff2126d to your computer and use it in GitHub Desktop.
Meteor Server Side PDF Generation
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