Help with returning data synchronously from PDFKit

Hi there, I’m trying to use PDFKit to create invoices server-side on my app and then return the final PDF data (as a buffer/stream?). The actual PDFKit seems quite logical but I’m struggling to return something synchronously from the method:

doc = new PDFDocument { margin: 50 }

doc.fontSize(10)
doc.text "Acme Corp"
doc.text "123, Main Street", { align: "right" }
doc.text "New York, NY", { align: "right" }

doc.end()

I’m thinking I’ll have to make use of Meteor.wrapAsync or Promises but I’m at a bit of a loss at writing the code in such a way as I can wait for the final document data to be ready before returning it to the client. Would anyone be able to help with any examples/tips?

Or if anyone has already had any experience creating the PDFs server-side. Thanks in advance!

import { Base64Encode } from 'base64-stream';
Meteor.methods({
    getPDF:()=> Promise.await(new Promise(( resolve, reject ) => 
    {
      let finalString = '';
      const doc = new PDFDocument { margin: 50 }
      const stream = doc.pipe(new Base64Encode());
      ....
      doc.end();
      stream.on('data',chunk => finalString += chunk );
      stream.on('end',()=>resolve(finalString));
    }))
});
3 Likes

Thank you very much! This works superbly for my needs, (only thing I changed was to return a Uint8Array before creating the blob on the front end.

I can’t confess to having my head around the promise and streaming involved so I’ll have to take a closer look and improve my knowledge in this area!

1 Like