Pdfmake: Format error: Not a PDF or corrupted

Created on 18 Oct 2017  路  1Comment  路  Source: bpampuch/pdfmake

I'm pdfmake to generate a pdf file in a nodejs environement(firebase functions). I used the following code:

const fs = require('fs')
var PdfPrinter = require('../node_modules/pdfmake/src/printer')
var path = require('path')

var fontDescriptors = {
    Roboto: {
      normal: path.join(__dirname, '../fonts/Roboto-Regular.ttf'),
      bold: path.join(__dirname, '../fonts/Roboto-Medium.ttf'),
      italics: path.join(__dirname, '../fonts/Roboto-Italic.ttf'),
      bolditalics: path.join(__dirname, '../fonts/Roboto-MediumItalic.ttf')
    }
  }

  var printer = new PdfPrinter(fontDescriptors);

// and you pass the doc-definition-object to createPdfKitDocument method
  var docDefinition = {
    content: [
      'First paragraph',
      'Another paragraph, this time a little bit longer to make sure, this line will be divided into at least two lines'
    ]
  };

  var pdfDoc = printer.createPdfKitDocument(docDefinition);
  pdfDoc.pipe(fs.createWriteStream('basics.pdf'));
  pdfDoc.end();

the basics.pdf file is being generated, but when I open it I get: "Format error: Not a PDF or corrupted"

I opened the generated pdf with a texteditor and the only thing I see there is this:
%PDF-1.3

Any ideas what I'm doing wrong?

Most helpful comment

It turns out, that it is some kind of a firebase issue. No idea why but it seems that you can't do this
pdfDoc.pipe(fs.createWriteStream('basics.pdf'));

For others stumbling on the same issue. Here is what I did as a workaround:

  let pdfDoc = printer.createPdfKitDocument(docDefinition);

  let buffers = [];


  pdfDoc.on('data', buffers.push.bind(buffers));
  pdfDoc.on('end', () => {
    let pdfData = Buffer.concat(buffers);

    fs.writeFileSync('basics.pdf', pdfData)
  })

  pdfDoc.end()

Writing the buffer to a file at the end works

>All comments

It turns out, that it is some kind of a firebase issue. No idea why but it seems that you can't do this
pdfDoc.pipe(fs.createWriteStream('basics.pdf'));

For others stumbling on the same issue. Here is what I did as a workaround:

  let pdfDoc = printer.createPdfKitDocument(docDefinition);

  let buffers = [];


  pdfDoc.on('data', buffers.push.bind(buffers));
  pdfDoc.on('end', () => {
    let pdfData = Buffer.concat(buffers);

    fs.writeFileSync('basics.pdf', pdfData)
  })

  pdfDoc.end()

Writing the buffer to a file at the end works

Was this page helpful?
0 / 5 - 0 ratings

Related issues

Masber picture Masber  路  3Comments

einfallstoll picture einfallstoll  路  3Comments

SummerSonnet picture SummerSonnet  路  3Comments

kumarandena picture kumarandena  路  3Comments

CharlyPoppins picture CharlyPoppins  路  3Comments