Chrome中的附加选项headless print-to-pdf

mcdcgff0  于 2023-03-27  发布在  Go
关注(0)|答案(6)|浏览(403)

我需要帮助一个更多的时间.我试图打印一个页面到PDF使用chrome的无头功能.然而,页眉和页脚是目前在PDF.我发现,这个选项已在Devtools实现.
https://chromedevtools.github.io/devtools-protocol/tot/Page/#method-printToPDF
但是,我找不到如何在CLI中使用这些选项。也可以从selenium调用Devtools吗?
另外,我如何在开发工具中调用Page.PrintToPDF。我试图在控制台中运行该命令。它显示页面未定义。

rryofs0p

rryofs0p1#

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

@media print {
  @page { margin: 0; }
  body { margin: 1.6cm; }
}

您应该像下面这样格式化您的命令以创建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"

例一:

C:\chrome-win/chrome --headless --disable-gpu --print-to-pdf=C:\user\fileName.pdf --no-margins C:\Projects\index.html

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

chrome --headless --disable-gpu --print-to-pdf https://www.chromestatus.com/
ws51t4hk

ws51t4hk2#

"/path/to/google-chrome":这是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:网页的url。
PDF页面格式(使用CSS)添加此(到css文件):

@media print {
            @page { margin: 0mm 0mm 0mm 0mm;
            size:8in 9.5in;
            }
            }

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

f2uvfpb9

f2uvfpb93#

如果您需要使用Chrome(或Edge)将页面打印为PDF,而没有页眉和页脚,则有一个额外的命令行选项:--print-to-pdf-no-header
有关所有命令行选项的完整列表,请参见:https://peter.sh/experiments/chromium-command-line-switches/

utugiqy6

utugiqy64#

CLI开关确实有文档记录。首先,对于原始/经典的chrome无头,它们位于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。

zour9fqk

zour9fqk5#

--no-pdf-header-footer标志背后的功能以前是通过--print-to-pdf-no-header标志提供的。根据您使用的Chrome版本,您可能需要回退到旧的标志名称。
对于新的无头chrome更新(日期为2023年2月)后的chrome更新版本。

fdbelqdn

fdbelqdn6#

是的,如果您想下载PDF格式的网页,需要添加此媒体查询。参考媒体打印CSS https://developer.mozilla.org/en-US/docs/Web/CSS/@media
页面CSS https://developer.mozilla.org/en-US/docs/Web/CSS/@page

相关问题