我有这个 NodeJs 应用程序,尝试从 HTML 生成 PDF。它可以在 Mac 上运行,但不能在 Windows 上运行(超时)。这是代码。
const puppeteer = require('puppeteer');
const fs = require('fs');
const init = async () => {
try {
const browser = await puppeteer.launch({headless: true});
const page = await browser.newPage();
await page.setContent('<h1>Hello World</h1>');
await page.emulateMediaType('screen');
await page.pdf({
path: 'hello-world.pdf',
format: 'A4',
printBackground: true,
timeout: 0
});
console.log('PDF Generated');
await browser.close();
process.exit()
} catch (error) {
console.log(error)
}
};
init()
调用page.pdf方法后,等待时间太长,超时。
ProtocolError: Page.printToPDF timed out. Increase the 'protocolTimeout' setting in launch/connect calls for a higher timeout if needed.
但在我的 M1 MacBook Pro 上,它就像一个魅力。
在 Windows 11 VM (Parallels) 和几台 Windows 11 笔记本电脑上尝试过此操作。但运气不佳。
我在这里做错了什么?我还需要添加其他东西吗?
谢谢!
节点:v20.15.0
傀儡师:^22.12.1
几个小时后我找到了问题。
使用浏览器日志记录启动浏览器后
await puppeteer.launch({headless: true, dumpio:true});
它记录了以下内容:
[16848:6956:0703/000025.226:ERROR:sandbox_win.cc(913)] Sandbox cannot access executable. Check filesystem permissions are valid. See [URL]: Access is denied. (0x5)
DevTools listening on ws://[URL][16848:7356:0703/000025.488:ERROR:network_service_instance_impl.cc(600)] Network service crashed, restarting service.
[16848:6956:0703/000026.330:ERROR:sandbox_win.cc(913)] Sandbox cannot access executable. Check filesystem permissions are valid. See [URL]: Access is denied. (0x5)
所以我发现添加
args: ['--no-sandbox', '--disable-setuid-sandbox']
是一种解决方法,但不推荐 https://stackoverflow.com/a/53975412/9814969
这似乎是基于 Linux 的系统上的常见问题,但我在 Windows 上尝试过。因此添加这个作为答案