【发布时间】:2020-11-23 04:49:41
【问题描述】:
从无头 chrome Playwright 会话(下面的代码)制作 PDF 时,我会在左侧获得 PDF,而如果我通过在 chrome 中保存为 pdf 来制作 PDF,则会获得第二个输出。
我已经明确设置了边距并使用了preferCSSPageSize: true,两者都给出了相同的(左)结果。
如何让 Playwright 从打印对话框中为我提供与 chrome 相同的输出?
files being printed is here 的示例。 (在现实生活中,考虑到书脊宽度,它们都略有不同。)
const fs = require("fs");
const path = require("path");
const { chromium } = require("playwright");
const directoryPath = "outside";
(async () => {
const filesToPrint = getFilesToPrintList(directoryPath);
filesToPrint.forEach((f, i) => console.log(i, f));
const browser = await chromium.launch({ headless: true });
const context = await browser.newContext();
for (let i = 0; i < filesToPrint.length; i++) {
const htmlFilename = path.join(directoryPath, filesToPrint[i]);
const pdfFilename = makePDFfilename(htmlFilename);
console.log("[html file]", htmlFilename);
console.log("[pdf file]", pdfFilename);
const page = await context.newPage();
await page.goto(
"file:///" + path.resolve(htmlFilename),
(waitUntil = "networkidle")
);
const options = {
path: pdfFilename,
pageRanges: "1",
preferCSSPageSize: true,
};
console.log(
`\n\nAbout to print:\n ${pdfFilename}\n`,
`with:\n${JSON.stringify(options, null, 2)}`
);
await page.pdf(options);
}
await browser.close();
console.log("done");
})();
function makePDFfilename(htmlFilename) {
const parts = htmlFilename.split(/[\\\._]/);
const pdfFilename = path.join(
directoryPath,
`Experimental_${parts[1]}_${parts[2]}.pdf`
);
return pdfFilename;
}
function getFilesToPrintList(directoryPath) {
let theFiles = fs
.readdirSync(directoryPath)
.filter((f) => f.includes("fp_") && f.includes(".html"));
return theFiles;
}
【问题讨论】:
-
我认为这个问题可以在 v1.12.3 上解决。我有类似的问题,但后来我意识到我使用的是旧版本的剧作家。使用 2021 年 7 月的最后一个版本,问题就消失了。
标签: node.js google-chrome chromium playwright css-print