Adding fonts to Puppeteer PDF renderer

瘦欲@ 提交于 2019-12-03 16:42:58

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 dependencies
RUN 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 /app
WORKDIR /app

# Copy package.json into app folder
COPY package.json /app

# Install dependencies
RUN npm install 

COPY . /app

# Start script on Xvfb
CMD ["xvfb-run","npm","start"]

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

.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!