Chrome无头打印到pdf的其他选项

use*_*925 22 pdf google-chrome google-chrome-headless

我再一次需要帮助.我正在尝试使用chrome的无头功能将页面打印为pdf.但是,页眉和页脚存在于pdf中.我发现这个选项已经在Devtools中实现了.

https://chromedevtools.github.io/devtools-protocol/tot/Page/#method-printToPDF

但是,我无法找到如何在CLI中使用这些选项.也可以从硒中调用Devtools?

另外,我如何在Dev工具中调用Page.PrintToPDF.我试图在Console中运行该命令.它显示页面未定义.

Aya*_*hid 12

"/path/to/google-chrome" : 这是谷歌浏览器的路径。

'--headless' : 无头环境中的 Chrome 浏览器,没有完整的浏览器 UI

'--run-all-compositor-stages-before-draw' :它在渲染所有数据之前阻止 Pdf 创建(在渲染所有数据后,将创建 pdf)。

'--virtual-time-budget = x: 它会延迟 Pdf 的创建过程,这里 x 将是毫秒。

'--print-to-pdf' :此标志创建给定 Url 的 pdf。

URL : 网页的网址。

PDF 页面格式(使用 CSS)添加这个(到 css 文件):

 @media print {
    ??      @page { margin: 0mm 0mm 0mm 0mm;
            size:8in 9.5in;
            }
            }
Run Code Online (Sandbox Code Playgroud)

以上CSS代码对网页渲染没有影响,只对PDF页面的格式有影响。


pre*_*ags 10

如果您需要使用 Chrome(或 Edge)将页面打印为 PDF,不带页眉和页脚,则还有一个附加命令行选项: --no-pdf-header-footer。仍然可以使用另一个选项--print-to-pdf-no-header ,尽管它现在已被弃用。

有关所有命令行选项的完整列表,请访问: https://peter.sh/experiments/chromium-command-line-switches/

  • --print-to-pdf-no-header 已弃用。请使用 **`--no-pdf-header-footer`** 代替。示例命令:`google-chrome --headless --print-to-pdf=file1.pdf --no-pdf-header-footer https://example.com` (2认同)

小智 8

将此CSS添加到您创建PDF的页面中,以删除Chrome Headless实现的页眉和页脚.

CSS:

@media print {
  @page { margin: 0; }
  body { margin: 1.6cm; }
}
Run Code Online (Sandbox Code Playgroud)

您应该像下面那样格式化命令以创建PDF:

"C:\PATH\TO\CHROME\EXECUTABLE\FILE", "--headless","--disable-gpu","--print-to-pdf=" + directory path to where you want the file to go followed by the desired file name/fileName.pdf,"--no-margins", "the path to the file you want turned into a pdf"
Run Code Online (Sandbox Code Playgroud)

例1:

C:\chrome-win/chrome --headless --disable-gpu --print-to-pdf=C:\user\fileName.pdf --no-margins C:\Projects\index.html
Run Code Online (Sandbox Code Playgroud)

例2:

您还可以通过在命令行中导航到包含Chrome可执行文件的文件夹并运行以下命令来测试此功能:

chrome --headless --disable-gpu --print-to-pdf https://www.chromestatus.com/
Run Code Online (Sandbox Code Playgroud)

编辑:修正错字

  • 这并没有正确解决多页PDF上的问题 - 它删除了除最后一页之外的所有页面的底部边距,以及除了第一页之外的所有页面上的上边距.我想除非你使用DevTools API,否则在没有打破多页边距的情况下无法做到这一点... (10认同)

cha*_*art 5

CLI 开关确实有记录。首先,对于原始/经典的 chrome headless,它们位于https://developer.chrome.com/blog/headless-chrome/#command-line-features
对于“新”引擎(自 2021 年起,通过 访问--headless=new),其开关位于https://developer.chrome.com/articles/new-headless/#headless-specific-command-line-flags