meteorpdf-generationflow-router

Meteor: Dynamic pdf generation with pdfKit and FlowRouter


I'm using pdfKit and FlowRouter on my meteor App. I would like to generate a pdf file without saving it an the server. In the docs there is an example for that:

Router.route('/getPDF', function() {
 var doc = new PDFDocument({size: 'A4', margin: 50});
 doc.fontSize(12);
 doc.text('PDFKit is simple', 10, 30, {align: 'center', width: 200});
 this.response.writeHead(200, {
 'Content-type': 'application/pdf',
 'Content-Disposition': "attachment; filename=test.pdf"
 });
 this.response.end( doc.outputSync() );
 }, {where: 'server'});

But this is for Iron Router usage. As I'm using FlowRouter, I don't know how to display/download the pdf directly to the user without saving the file on the server.


Solution

  • Use the server side router from meteorhacks picker. Then something along the lines of

    Picker.route('/generate/getPdf', function(params, req, res, next) {
        var doc = new PDFDocument({size: 'A4', margin: 50});
        doc.fontSize(12);
        doc.text('PDFKit is simple', 10, 30, {align: 'center', width: 200});
        res.writeHead(200, {
            'Content-Type': 'application/pdf',
            'Content-Disposition': 'attachment; filename=test.pdf'
        });
        res.end(doc.outputSync());
    });
    

    UPDATE: now that outputSync is deprecated, use:

    Picker.route('/generate/getPdf', function(params, req, res, next) {
        var doc = new PDFDocument({size: 'A4', margin: 50});
        doc.fontSize(12);
        doc.text('PDFKit is simple', 10, 30, {align: 'center', width: 200});
        res.writeHead(200, {
            'Content-Type': 'application/pdf',
            'Content-Disposition': 'attachment; filename=test.pdf'
        });
        doc.pipe(res);
        doc.end();
    });