对于 Debian 系的发行版(比如 Ubuntu)需要先安装以下依赖:

apt install gconf-service libasound2 libatk1.0-0 libatk-bridge2.0-0 libc6 libcairo2 libcups2 libdbus-1-3 libexpat1 libfontconfig1 libgcc1 libgconf-2-4 libgdk-pixbuf2.0-0 libglib2.0-0 libgtk-3-0 libnspr4 libpango-1.0-0 libpangocairo-1.0-0 libstdc++6 libx11-6 libx11-xcb1 libxcb1 libxcomposite1 libxcursor1 libxdamage1 libxext6 libxfixes3 libxi6 libxrandr2 libxrender1 libxss1 libxtst6 ca-certificates fonts-liberation libappindicator1 libnss3 lsb-release xdg-utils wget 

这些发行版的 server 版本通常是没有预装中文字体的,网页里的中文部分会变成方块,所以还需要先安装中文字体

# 这里的 fonts 目录需要根据你的实际情况自行调整,你也可以直接将字体放到 /usr/share/fonts/truetype/ 目录下 cp -R fonts/* /usr/share/fonts/truetype/ fc-cache -f -v 

然后就可以创建项目目录和安装 puppeteer 了:

mkdir puppeteer-demo cd puppeteer-demo yarn add puppeteer touch index.js 

编辑 index.js 为如下内容:

async function printPDF() {  const browser = await puppeteer.launch({ args: ['--no-sandbox'] }) const page = await browser.newPage() await page.setViewport({ width: 1920, height: 1200 }) await page.goto('http://www.qq.com/') await page.pdf({ path: 'page.pdf', format: 'Tabloid', printBackground: true }) await browser.close() } printPDF()

如果是以 root 用户启动 puppeteer,需要增加 --no-sandbox 启动参数

const browser = await puppeteer.launch({ args: ['--no-sandbox'] }) 

最后执行 node index.js 完毕就可以看到当前目录下的 page.pdf 文件了

相关资料

  1. https://github.com/GoogleChrome/puppeteer/blob/master/docs/api.md#pagepdfoptions
  2. Puppeteer 提供的一份常见问题以及解决方案列表
要获得最佳阅读体验,请访问原文 https://baiyun.me/use-puppeteer-to-print-pdf-on-linux