Chrome Headless打印PDF无日期时间戳问题求助
解决Chrome Headless打印PDF丢失日期时间戳的问题
问题原因
Chrome的Headless打印PDF功能在版本迭代中调整了默认页眉页脚配置,此前默认包含的创建日期时间戳现在默认不再显示;同时谷歌搜索页面的打印样式也可能影响了页眉页脚的展示效果。
解决方案
1. 显式指定自定义页眉/页脚模板
利用Chrome Headless的--print-to-pdf-header-template或--print-to-pdf-footer-template参数,通过HTML模板强制添加日期和时间戳。
示例命令:
chrome --headless --print-to-pdf="C:\Test\file32.pdf" --print-to-pdf-header-template="<div style='font-size:10px; width:100%; text-align:center;'>Created: <span class='date'></span> <span class='time'></span></div>" https://www.google.com/search?q=chrome+headless
- 模板里的
<span class='date'></span>和<span class='time'></span>是Chrome内置占位符,会自动替换为PDF生成时的日期与时间。 - 你可以调整模板的字体大小、对齐方式等样式,匹配自己的需求。
2. 还原类旧版默认页眉页脚
如果需要保留包含标题、URL、日期时间的完整默认样式,可以使用更全面的模板:
chrome --headless --print-to-pdf="C:\Test\file32.pdf" --print-to-pdf-header-template="<div style='font-size:10px; padding:0 10px; width:100%; display:flex; justify-content:space-between;'><span class='title'></span><span class='date'></span> <span class='time'></span></div>" --print-to-pdf-footer-template="<div style='font-size:10px; padding:0 10px; width:100%; display:flex; justify-content:space-between;'><span class='pageNumber'></span>/<span class='totalPages'></span><span class='url'></span></div>" https://www.google.com/search?q=chrome+headless
该模板会还原类似旧版本的页眉(标题+日期时间)和页脚(页码+页面URL)。
3. 排除页面样式干扰
如果自定义模板仍不生效,可能是页面打印CSS隐藏了页眉页脚区域,可以尝试添加--disable-print-preview参数,不过这种情况概率较低,优先尝试前两种模板方案。
内容的提问来源于stack exchange,提问作者mean_
相关产品推荐
相关产品推荐

