Tuesday 14 March 2017

Can you insert a PDF generated by PDFKit into a MongoDB collection?

I'm generating a PDF using the PDFKit library and I would like to insert the generated PDF into a MongoDB collection. On the client side a user should be able to see the list of files in the collection and choose one of these files to download.

As of now I'm saving the PDF in the collection as a Uint8Array and I can then click on the file at the front end to download it.

However, my problem is that the file seems to be corrupt. It will not open in Adobe Reader or in Chrome. I've tried saving it to the collection with and without PDFKits compression.

Is this possible to do? Or do I have a bad approach to this.
Any help with this would be great and thanks in advance!

Server Side
Most of the code here is based off of this post on the PDFKit GitHub

  var doc = new PDFDocument();
  var stream = require('stream');
  var converter = new stream.PassThrough();
  doc.pipe(converter);

  var data = [];
  converter.on('data', function(chunk) {
    data.push(chunk);
  });

  converter.on('end',  Meteor.bindEnvironment( function () {
    var buffer = Buffer.concat(data);
    PdfFiles.insert({ data:buffer, userID:userId });
  }));

  // Adding content to the PDF

  doc.end();

Client Side

'click .downloadPDF': function (event) {
    event.preventDefault();

    var file = UserFiles.findOne({userID:Meteor.userId()});

    var FileSaver = require('file-saver');
    var blob = new Blob(file.data, {type: "application/pdf"});
    FileSaver.saveAs(blob, "AwesomePDF");
}



via Dowling1dow

No comments:

Post a Comment