Adding fonts to Puppeteer PDF renderer Adding fonts to Puppeteer PDF renderer docker docker

Adding fonts to Puppeteer PDF renderer


This is a sample script which goes and captures screenshot and pdf on website. Both serves same purpose on this question, to show the fonts works.

(async()=>{  const puppeteer = require('puppeteer')  const browser = await puppeteer.launch({    headless: true,    args: ["--no-sandbox", "--disable-setuid-sandbox"]  });  const page = await browser.newPage()  await page.goto('https://jp.quora.com/')  await page.screenshot({path: `/shared/_${Date.now()}.png`})  const pdfBuffer = await page.pdf({path: `/shared/_${Date.now()}.pdf`});  await browser.close()})()

Here is the minimal dockerfile, this is very minimal, it doesn't include anything extra like dumb-init and various cleanup hacks as it's not required here.

FROM node:8# Install dependenciesRUN apt-get update && \apt-get -yq install libatk1.0-0 libgtk2.0-0 libnotify-dev libgconf-2-4 libnss3 libxss1 libasound2 libxtst6 libasound2 xauth xvfb # Cd into /appWORKDIR /app# Copy package.json into app folderCOPY package.json /app# Install dependenciesRUN npm install COPY . /app# Start script on XvfbCMD ["xvfb-run","npm","start"]

Upon running, here is how Japanese Quora is showing on puppeteer, it is showing like this because fonts are missing.

enter image description here.

Since it is based on jessie, and we can install fonts using few different commands.

Run standard apt-get

The below will install some fonts with Japanese characters in it.

RUN apt-get -yq install xfonts-utils fonts-droid xfonts-intl-asian

Copy fonts from directory

If I have the fonts inside fonts directory, then the command is,

COPY fonts/*.* /usr/share/fonts/truetype/

That's really straightforward. However the fonts will still not work because the font cache is not updated that fast enough. Adding the following will make sure it's updated.

RUN mkfontscale && mkfontdir && fc-cache

That's it! Let us run the script again.

enter image description here