Puppeteer using google fonts in headers and footer in Node.js serverless AWS lambda

Viewed 1241

I am using Node.js AWS lambda with serverless framework, The PDF generation is working fine, Now I have a requirement to use custom fonts in headers and footer section, I have tried to add the google fonts using layer in serverless and also tried to import the fonts through css it's is not working in both ways does anyone knows how can we use custom fonts in Header and Footer using puppeteer.

Below is my helper class that generates the PDF:

import * as chromium from "chrome-aws-lambda";
import { GetPDFBuffer } from "./types/HelperTypes";

export class Helper {
  static getPDFBuffer: GetPDFBuffer = async (html: string, options: any) => {
    let browser = null;
    try {
      const executablePath = process.env.IS_OFFLINE
        ? null
        : await chromium.executablePath;
      browser = await chromium.puppeteer.launch({
        args: chromium.args,
        executablePath,
      });

      const page = await browser.newPage();
      const loaded = page.waitForNavigation({
        waitUntil: "networkidle0",
      });
      await page.setContent(html, { "waitUntil": ['load', 'domcontentloaded', 'networkidle0'] });
     
      await loaded;
      return await page.pdf(options);
    } catch (error) {
      return error;
    } finally {
      if (browser !== null) {
        await browser.close();
      }
    }
  };
}  
1 Answers

Headers and footers have some limitations regarding external styling.

If you want to use a custom google font, you'll have to download the font and install it as a system font and chrome will pick it up automatically from your font-family rule.

Example:

  1. Download https://fonts.google.com/specimen/Open+Sans
  2. Install the font per your OS's instructions. Font Book is used on a mac for example.
  3. Reference the font as you would any other system font in your header or footer:
<style>
  footer {
    font-family: 'Open Sans', sans-serif;
  }
</style>
Related