question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

[BUG] Unable to generate pdf from html (aws lambda)

See original GitHub issue

Problem statement

I’m creating a lambda function to generate PDF from HTML, I haven’t installed Puppeteer. Is that possible to generate pdf without downloading chrome or chromium or any browser?

To reproduce kindly use the following request payload.

curl --location --request POST 'http://127.0.0.1:3000/dev/convert' \
--header 'Content-Type: application/json' \
--data-raw '{
    "header" : "<h1 style=\"margin-top:10px;font-size:40px\">Header is here<\/h1>",
    "html": "<!DOCTYPE html><html><body><h1>This is a heading<\/h1><p>This is a paragraph.<\/p><\/body><\/html>",
    "footer": "<p style=\"margin-top:10px;font-size:20px\">This is footer<\/p>"
}'

Environment

  • chrome-aws-lambda Version: ^3.1.1
  • puppeteer-core Version: ^4.0.0
  • OS: Linux
  • Node.js Version: 12.x
  • Serverless Version: ^1.73.1
  • aws-sdk Version: ^2.700.0
  • Lambda / GCF Runtime: nodejs12.x

Expected Behavior

Should generate pdf from html

Current Behavior

Not generating pdf

Steps to Reproduce

const chromium = require("chrome-aws-lambda");
const AWS = require("aws-sdk");


exports.htmlToPdfNode = async (event, context, callback) => {
  try {

    
    let requestBody = (typeof event.body == typeof 'string' ? JSON.parse(event.body) : event.body);
    
    const pdf = generatePdf(requestBody);
    
    uploadToS3(pdf);

    const response = {
      headers: {
        "Content-type": "application/pdf",
        "content-disposition": "attachment; filename=test.pdf"
      },
      statusCode: 200,
      body: pdf,
      isBase64Encoded: true,
    };

    

    callback(null, response);
    
  } catch (err) {
    callback(null, err);
  }
};


async function generatePdf(requestBody) {
  const headerHtml = requestBody.header;
  const bodyHtml = requestBody.html;
  const footerHtml = requestBody.footer;

  let browser = null;
    
  
  browser = await chromium.puppeteer.launch({
    // ignoreHTTPSErrors: true,
    // defaultViewport: chromium.defaultViewport,
    // args: chromium.args,
    // executablePath: await chromium.executablePath,
    args: ['--no-sandbox'],
    headless: true, //chromium.headless,
  });
  
  const page = await browser.newPage();
  await page.setContent(bodyHtml);
  
  // 4. Create pdf file with puppeteer
  const pdf = await page.pdf({
    format: "A4",
    printBackground: true,
    displayHeaderFooter: true,
    margin: { top: "100px", bottom: "200px" },
    headerTemplate: headerHtml,
    footerTemplate: footerHtml,
  });

  
  await browser.close();

  return pdf.toString('base64');
}


async function uploadToS3(pdf) {
  let s3 = new AWS.S3();
  let bucketName = process.env.Bucket;
  let keyName = "test/test.pdf";

  console.log('bucketName : '+ bucketName);

  let params = { Bucket: bucketName, Key: keyName, Body: pdf, ContentType: 'application/pdf' };
  s3.upload(params, function(err, data){
    console.log(err, data);
  });

}

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Comments:5

github_iconTop GitHub Comments

1reaction
jessefalzonecommented, Jul 15, 2020

I ran into a similar issue. Try awaiting generatePdf, like so:

const pdf = await generatePdf(requestBody);
uploadToS3(pdf);

That worked for me.

0reactions
saurabhcgcommented, Jul 5, 2020

–header ‘Content-Type: application/pdf’ \

Already did.

Read more comments on GitHub >

github_iconTop Results From Across the Web

html-pdf package is not working on aws lambda - Stack Overflow
I have tried implementing html-pdf package in my code which is deployed at AWS lambda but getting error in it even after I...
Read more >
How to generate PDF from HTML on AWS Lambda
Anyone had luck in creating a function for html to pdf generation on AWS? The closest I could get was using wkhtmltopdf and...
Read more >
Troubleshoot deployment issues in Lambda
Create a deployment artifact bucket for each Region where you develop applications. General: Cannot find, cannot load, unable to import, class not found,...
Read more >
Building a PDF Generator using AWS Lambda
A user can easily tamper with the HTML content beforehand and compile the PDF in the client application before sending it to the...
Read more >
Building a PDF Generator on AWS Lambda with Python3 and ...
This command will bootstrap a Python3 Lambda setup for you to work from. WKHTMLTOPDF Binary. Next, we need to get the binary for...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found