how to create pdf from html with @sparticuz/chrome-aws-lambda

Viewed 10

I am trying to create a pdf from a page, the problem is that the pdf is empty.

this is my code:

const chromium = require("@sparticuz/chrome-aws-lambda");

exports.handler = async (event) => {
    
    let browser = await chromium.puppeteer.launch({
      args: chromium.args,
      defaultViewport: chromium.defaultViewport,
      executablePath: await chromium.executablePath,
      headless: chromium.headless
     });
    let page = await browser.newPage();
    await page.goto("https://www.google.com");

    const pdf = await page.pdf({ 
      format: "A4",
      printBackground: false,
      preferCSSPageSize: true,
      displayHeaderFooter: false,
    
      headerTemplate: `<div class="header" style="font-size:20px; padding-left:15px;"><h1>Main Heading</h1></div> `,
      footerTemplate: '<footer><h5>Page <span class="pageNumber"></span> of <span class="totalPages"></span></h5></footer>',
      margin: { top: "200px", bottom: "150px", right: "20px", left: "20px" },
      height: "200px",
      width: "200px",
    });
    
    browser.close();
    return {
        statusCode: 200,
        //  Uncomment below to enable CORS requests
        headers: {
            //"Access-Control-Allow-Origin": "*",
            //"Access-Control-Allow-Credentials": true,
            "Content-type": "application/pdf",
            "content-disposition": "attachment; filename=test.pdf"
        },
        body: pdf.toString()
        };
      };

here i am trying to convert google html to pdf but its not working my pdf is empty, here is an example.

enter image description here

If a try to put pdf.toString('base64') I get an error in my pdf.

enter image description here

These errors occur even though I put some basic HTML on the page like this

 await page.setContent(<html><body><h1>Hello!</h1></body></html>, { waitUntil: "domcontentloaded" });
0 Answers
Related