Base64 to Pdf export issue AWS Lambda

1.9k Views Asked by At

I'm creating pdf document using AWS Lambda Puppeteer Nodejs package.

const page = await browser.newPage()
page.setContent(html)

const pdf = await page.pdf({
  format: 'A4',
  printBackground: true,
  margin: { top: '1cm', right: '1cm', bottom: '1cm', left: '1cm' }
})

var pdf_base64 = await pdf.toString('base64');

const response = {
 headers: {
   'Content-Type': 'application/pdf',
   'Content-Disposition': 'attachment;filename=downloaded.pdf'
  },
 statusCode: 200,
 body: pdf_base64,
 isBase64Encoded: true
}

Pdf is getting downloaded but seems corrupted or not properly encoded. While opening chrome shows Failed to load PDF document.

But, if i remove headers and export the base 64 & save it to pdf using any online service proper pdf is generated and working.

Even if i open downloaded pdf using text-editor and copy the base64 content and re-generated pdf from base64 using any online tool it works.

What can be the issue while returning.

1

There are 1 best solutions below

1
jpheos On BEST ANSWER

I'am new on serverless, so I can't really explain how it's works. But I had the same problem of you, and I add this on serverless.yml and now it's work:

plugins:
  - serverless-offline
  - serverless-apigw-binary

custom:
  apigwBinary:
    types:          
      - 'application/pdf'

Resource that helped me: https://github.com/maciejtreder/serverless-apigw-binary#readme