node.js - PrintToPDF 无法在 headless Chrome 60 中工作

标签 node.js google-chrome pdf-generation google-chrome-devtools centos7

我正在尝试通过 headless Chrome 进行 PDF 打印。这是我正在处理的错误:

(node:6761) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: PrintToPDF is not implemented

Node.js 包:

html-pdf-chrome

依赖关系:

✔ "chrome-remote-interface": "^0.23.1"  (v0.23.2 installed)   
✔ Chrome 59  (v60 beta installed)

驱动程序脚本:

const htmlPdf = require('html-pdf-chrome');
const html = '<p>Hello, world!</p>';
const options = {
    port: 9222, // port Chrome is listening on
};
htmlPdf.create(html, options).then((pdf) => pdf.toFile('test.pdf'));

Chrome 60 已安装并以 headless 模式运行:

> google-chrome --version
Google Chrome 60.0.3112.24 beta

我已经追踪到调用 Page.printToPDF 的代码部分,这是引发错误的地方:

const CDP = require("chrome-remote-interface");
...
const { Page } = client;
...
// https://chromedevtools.github.io/debugger-protocol-viewer/tot/Page/#method-printToPDF
const pdf = yield Page.printToPDF(options.printOptions);

我能够毫无失败地执行其他广告功能,例如 Page.captureScreenshot

如何让 Page.printToPDF 按广告执行?

最佳答案

以下是我如何在 PHP 中创建 headless Chrome 命令以在 apache 用户下运行 Chrome:

private $headlessChromeCmd = [
    '$(which google-chrome)',
    '--headless',
    '--disable-gpu',
    '--hide-scrollbars',
    '--remote-debugging-port=%u',
    '--no-first-run',
    '--safebrowsing-disable-auto-update',
    '--disable-background-networking',
    //'--disable-extensions', <-- This was the problem
    '--disable-translate',
    '--disable-sync'
];

...

// Launch Chrome in a non-blocking background process
$cmd = sprintf(implode(' ', $this->headlessChromeCmd), $port) . ' < /dev/null >"'. $this->chromeStdoutFile . '" 2>&1 & echo $!;';

// For brevity without capturing stdout, stderr nor response codes
shell_exec($cmd);

CLI 参数 --disable-extensions 是罪魁祸首。生成 PDF 所需的 Chrome 的 PDF 查看器是此参数禁用的扩展之一。谜团解开了。

关于node.js - PrintToPDF 无法在 headless Chrome 60 中工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44480595/

相关文章:

node.js - 为什么我应该在 Google Nodejs 客户端库的 Actions 中使用dialogflow() 而不是 actionssdk()

api - JSON错误响应,有条件的疯狂

node.js - 推送通知 RESTful WebApp Angular2/NodeJS

javascript - 如何有条件地从 MongoDB 中的对象数组中删除一个字段?

C# - iTextSharp 该文档没有页面

javascript - 如何修复 chrome 扩展程序中的 'Chrome Content Security Policy Directive'

Java Selenium 路径

javascript - Chrome 中的状态是什么

php - 我可以让用户提交表格并收到 PDF 副本吗?

php - Docx 到 pdf 使用 openoffice headless 方式太慢