0
点赞
收藏
分享

微信扫一扫

利用Chrome Headless模式,网页转PDF


   原来一直是用wkhtmltopdf来将网页打印成PDF文件,它是基于QtWebKit内核的。但最近有个很奇怪
的字体问题困扰着我。所以找找其它能在Linux下实现相同功能的方法。然后发现Chrome Headless模式可
以实现我想要的,而且用Chrome来实现,可以排除掉很多Bug怀疑。
    Chrome Headless模式相当于一个没有界面的浏览器,能实现很多功能,能实现pdf打印,截图等,扩展下,可以
  做web测试,爬虫抓取等等。

CentOS 7下的安装:

# vi /etc/yum.repos.d/chrome.repo
[google-chrome]
name=google-chrome
baseurl=http://dl.google.com/linux/chrome/rpm/stable/$basearch
enabled=1
gpgcheck=1
gpgkey=https://dl-ssl.google.com/linux/linux_signing_key.pub


# yum info google-chrome-stable
# yum install -y google-chrome-stable
# yum install -y mesa-libOSMesa mesa-libOSMesa-devel gnu-free-sans-fonts
# yum install -y ipa-gothic-fonts ipa-pgothic-fonts

准备一个网页:

<!DOCTYPE html>
<html>
<head>
<style>
body {
width: 910px;
height: 1280px;
font-family: Arial;
background-image: url("http://www.xxx.com/UploadFiles/33/sss.png");
}

@page {
size: A4;
margin: 0;
}

@media print {
body {-webkit-print-color-adjust: exact;}
.no-print {display: none;}
}

</style>
</head>
<body>
<h1>test</h1>
<p style="font-family:Arial;font-size:18px;color:red">Arial:18px</p> <br/><br/>
</body>
</html>


打印成PDF:


google-chrome --headless --disable-gpu --print-to-pdf='cc5.pdf' http://127.0.0.1:8097/pdf


google-chrome --headless --disable-gpu --screenshot --window-size=800,1000 http://127.0.0.1:8097/pdf




"--print-to-pdf" 参数只是负责把网页转成PDF,如果想把网页打印成A4大小,并把背景图片显示出来,


记得在css中加上下面两条:


打印背景图片:


   -webkit-print-color-adjust: exact 


指定纸张大小:


    @page {size: A4;} 






参考链接:


​​Getting Started with Headless Chrome ​​






举报

相关推荐

0 条评论