Broken Font on AWS Lambda

Rendering a PDF document in Linux could result in broken characters, as shown in the image below. Sometimes the characters appear to render properly on a Windows environment, but not on Linux.

Broken Character

Reason

The reason is that the font is missing from the operating system.

Solutions

If you already know the font name, that's great—you can skip step 1.

  1. To find the font name, try rendering the HTML on Windows and use Adobe to inspect the characters.
  2. Once the font name is identified, you can download the font file online, such as from Google Fonts.
  3. To add and install the font via the Dockerfile, place the font in the project and set 'Copy to Output Directory' to 'Copy Always.' Next, use the following code to add and install it in the Dockerfile:
# Copy the Cambria Math font into the container
# Ensure the font file (cambria.ttc) exists in your project directory
COPY cambria.ttc /usr/share/fonts/

# Install fontconfig to update the font cache
# This will install fontconfig and refresh the font cache to recognize the newly added fonts
RUN dnf install -y fontconfig && \
    fc-cache -fv

Explanation

  • COPY cambria.ttc /usr/share/fonts/: This line copies the Cambria Math font from your project directory into the container's fonts directory. Make sure that the font file (cambria.ttc) is present in the project directory.

  • RUN dnf install -y fontconfig && \: This command installs the fontconfig package, which is necessary for managing and configuring font access in Linux. The -y flag automatically confirms the installation of the package.

  • fc-cache -fv: This command updates the font cache, ensuring that the newly copied fonts are available to applications within the container. The flags -f (force) and -v (verbose) are used to force a re-generation of the cache and provide a detailed output, respectively.