Управление полями при создании PDF-файла с помощью Playwright - PullRequest
1 голос
/ 03 августа 2020

При создании PDF-файла из безголового chrome сеанса драматурга (код ниже) я получаю PDF-файл слева, тогда как если я сохраняю его в формате pdf в chrome, я получаю второй результат.

enter image description here

I have set the margins explicitly and used preferCSSPageSize: true and both give the same (left) outcome.

How would I get Playwright to give me the same output as chrome does from the print dialog?

An example of the печатаемых файлов находится здесь . (В реальной жизни все они немного отличаются из-за ширины корешка.)

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;
}

1 Ответ

0 голосов
/ 09 августа 2020

Я попытался воспроизвести вашу проблему:

Я использовал другой URL-адрес фонового изображения (онлайн) с вашей HTML страницей, см. тест. html gist.

По-видимому, по умолчанию установлен ряд параметров. См. page.pdf().

Также добавлены browser.newContext() и browser.close().

Вот минимальный рабочий NodeJS код:

generate-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 ):

test.pdf

Возможно, вы захотите протестировать это отдельно и посмотреть, работает ли он для вашего варианта использования.

...