javascriptnode.jscloudinarypdfmake

How to upload the PDF file generated by pdfmake library to the cloudinary in nodejs?


I am trying to generate a Invoice PDF file from the order data that I receive in the create order API, and then upload that generated Invoice PDF file to the cloudinary.

I am able to successfully generate the Invoice PDF file from the order data that I receive, and when I try to upload it to the cloudinary it is getting uploaded and I am getting a secure_url from cloudinary, but when I open that url in the browser it says Failed to load PDF document. I am attaching my code below, please help me figure out where I am going wrong.

  // Generate the PDF buffer using pdfmake
  const pdfBuffer = await new Promise((resolve, reject) => {
    const pdfmakes = new pdfmake(fonts);
    const doc = pdfmakes.createPdfKitDocument(documentDefinition, {});
    const chunks: any = [];
    doc.on('data', (chunk: any) => chunks.push(chunk));
    doc.on('end', () => resolve(Buffer.concat(chunks)));
    doc.end();
  });

  const tempFilePath = path.join(os.tmpdir(), 'temp.pdf');
  fs.writeFileSync(tempFilePath, pdfBuffer);

  const uploadResult = await cloudinary.v2.uploader.upload(tempFilePath, {
    folder: 'invoices',
    resource_type: 'auto',
  });

  console.log('upload result', uploadResult);


Solution

  • Worth logging into your Cloudinary account, going to Settings -> Security tab and ensuring you've enabled the PDF/ZIP file delivery as detailed in the following Support Article:

    https://support.cloudinary.com/hc/en-us/articles/360016480179-PDF-or-ZIP-files-appearing-in-Media-Library-but-download-URLs-return-an-error-