从无头 chrome Playwright 会话(下面的代码)制作 PDF 时,我在左侧得到 PDF,而如果我通过在 chrome 中保存到 pdf 来完成它,我得到第二个输出。
我已经明确设置并使用了边距,preferCSSPageSize: true
并且两者都给出了相同的(左)结果。
我如何让 Playwright 从打印对话框中为我提供与 chrome 相同的输出?
正在打印的文件的示例在这里。(在现实生活中,考虑到脊椎宽度,它们都略有不同。)
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;
}