2

从无头 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;
}
4

1 回答 1

1

我试图重现您的问题:

我在您的 HTML 页面中使用了不同的背景图片 URL(在线),请参阅test.html要点。

显然,许多选项是默认值。见page.pdf()

此外,还添加了browser.newContext()browser.close()

这是最小的工作 NodeJS 代码:

生成-pdf.js

const { chromium } = require("playwright");

(async () => {
    const htmlFilename = "file:///<file-path>/test.html";
    console.log("[webpage]", htmlFilename);

    const browser = await chromium.launch();
    const context = await browser.newContext();
    const page = await context.newPage();
    await page.goto(htmlFilename);

    const pdfFilename = "./test.pdf";
    console.log("[pdf file]", pdfFilename);

    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");
})();

控制台输出:

$ node generate-pdf.js
[webpage] file:///<file-path>/test.html
[pdf file] ./test.pdf


About to print:
  ./test.pdf
 with:
{
  "path": "./test.pdf",
  "pageRanges": "1",
  "preferCSSPageSize": true
}
done

PDF ( test.pdf ) 的快照:

测试.pdf

您可能想单独测试它,看看它是否适用于您的用例。

于 2020-08-09T09:58:29.470 回答