You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js(Egg.js)用Puppeteer转PDF报错,求解决方案及替代工具

问题描述

在Node.js(egg-scripts环境)中使用puppeteer@^21.1.1进行HTML转PDF时,出现以下报错:

Error: Failed to launch the browser process!
/home/pi/.cache/puppeteer/chrome/chrome-linux64/chrome: 1: Syntax error: ")" unexpected
TROUBLESHOOTING: https://pptr.dev/troubleshooting

报错栈:

at Interface.onClose (/api/node_modules/@puppeteer/browsers/lib/cjs/launch.js:277:24)
at Interface.emit (node:events:539:35)
at Interface.close (node:readline:586:8)
at Socket.onend (node:readline:277:10)
at Socket.emit (node:events:539:35)
at endReadableNT (node:internal/streams/readable:1345:12)
at processTicksAndRejections (node:internal/process/task_queues:83:21)

实现代码:

async convertHtmlToPdf(orderId) {
const outputPath = path.join(this.config.baseDir, "app/public", "order_pdf_" + 123 + ".pdf");
console.log(outputPath);
const htmlContent = `
    <html>
      <body>
        <h1>Hello, World!</h1>
        <p>This is a sample HTML content to be converted to PDF.</p>
      </body>
    </html>
  `;
const browser = await puppeteer.launch();
const page = await browser.newPage();
// Set the HTML content of the page
await page.setContent(htmlContent, { waitUntil: 'domcontentloaded' });
// Generate PDF from the page
await page.pdf({ path: outputPath, format: 'A4' });
await browser.close();
}
解决方法

修复Puppeteer当前报错

报错核心原因是树莓派(ARM架构)环境下,Puppeteer默认下载的是x86_64架构的Chrome,无法兼容运行。解决步骤:

  1. 安装系统原生的Chromium浏览器:
sudo apt-get update && sudo apt-get install chromium-browser
  1. 修改代码中puppeteer.launch()的参数,指定系统Chromium的执行路径,并添加必要的沙箱禁用参数:
const browser = await puppeteer.launch({
  executablePath: '/usr/bin/chromium-browser',
  args: ['--no-sandbox', '--disable-setuid-sandbox']
});
  1. (可选)也可以通过设置环境变量PUPPETEER_EXECUTABLE_PATH=/usr/bin/chromium-browser,避免在代码中硬编码路径。

替代方案:其他HTML转PDF工具

如果不想折腾Puppeteer的架构兼容问题,可以尝试以下轻量工具:

  • html-pdf:基于PhantomJS,适合简单HTML转PDF场景,安装后直接调用:
npm install html-pdf
const pdf = require('html-pdf');
const htmlContent = '<h1>Hello World</h1>';
pdf.create(htmlContent).toFile('./order_pdf_123.pdf', (err, res) => {
  if (err) console.error(err);
});
  • wkhtmltopdf:基于webkit的命令行工具,支持复杂CSS和HTML布局,需先安装系统级工具:
sudo apt-get install wkhtmltopdf
npm install wkhtmltopdf
const wkhtmltopdf = require('wkhtmltopdf');
wkhtmltopdf('<h1>Hello World</h1>', { output: './order_pdf_123.pdf' });
  • pdfkit:适合需要自定义PDF结构的场景,需手动构建内容而非直接转HTML:
npm install pdfkit
const PDFDocument = require('pdfkit');
const fs = require('fs');
const doc = new PDFDocument();
doc.pipe(fs.createWriteStream('./order_pdf_123.pdf'));
doc.fontSize(25).text('Hello World', 100, 100);
doc.end();

内容的提问来源于stack exchange,提问作者Junaid Ali Ansari

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 08:40:30