zl程序教程

您现在的位置是:首页 >  其他

当前栏目

Google Chrome Headless (网页保存为PDF、网页截图)

2023-03-07 09:43:13 时间

一、Linux安装Chrome浏览器

yum install https://dl.google.com/linux/direct/google-chrome-stable_current_x86_64.rpm

二、指定网页打印成PDF

google-chrome --headless --disable-gpu --no-sandbox --print-to-pdf=gen.pdf http://www.google.com

三、指定网页截图

google-chrome --headless --disable-gpu --no-sandbox --screenshot=/home/a.jpg --window-size=1920,3550 https://nicen.cn

四、输出网页的HTML代码

google-chrome --no-sandbox --headless --disable-gpu --dump-dom https://www.baidu.com/

五、参数详解

所有参数的值以“=值”的形式提交。

1.--no-sandbox ,为通常为沙盒的所有进程类型禁用沙箱。 2.--headless ,在无头模式下运行,即没有UI或显示服务器依赖性。 3.--disable-gpu ,禁用GPU硬件加速。如果软件渲染器不到位,则GPU进程将无法启动。 4.--screenshot,保存已加载页面的屏幕截图。 5.--print-to-pdf,保存已加载页面的pdf文件。 6.--window-size,设置初始窗口大小。提供格式为“800,600”的字符串。 7.--timeout,在指定的毫秒数后发出停止。这将取消所有导航并导致DOMContentLoaded事件触发。 8. --incognito,使用无痕模式打开页面。

Chrome浏览器启动参数大全(命令行参数):https://www.cnblogs.com/gurenyumao/p/14721035.html

去除打印pdf时网页的页眉页脚,需要在网页的css中加入以下代码:

<style>
@media print {
  @page { margin: 0; }
  body { margin: 1.6cm; }
}
</style>