这篇文章主要介绍“HTMl转PDF的方法”,在日常操作中,相信很多人在HTMl转PDF的方法问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”HTMl转PDF的方法”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!
背景
公司需要将官网上的文章都打包成pdf,由于文章是通过后台富文本生成的,内容中带有HTML标签。所以只能够将内容放到html中,然后再下载。
HTML转PDF调研
1. iText
iText是非常著名的快速产生PDF文件的Java类库
2.Flying Saucer
Flying Saucer 用纯 Java 编写的,可以将 XML/XHTML 应用 CSS2.1 样式渲染为 PDF、图片。此库基本上能实现 CSS 2.1 的整体性, 并且完全符合 W3C 规范。
3.wkhtmltox
wkhtmltox是一个工具,类似饭桶(phantomjs)的工具
wkhtmltox
为什么要介绍上面这些呢?
下载wkhtmltox
官网下载地址: https://wkhtmltopdf.org/downloads.html

linux上安装并使用
上传wkhtmltox到服务器
rz
解压、安装(tar -Jxf)
解压xz文件: xz -d wkhtmltox-0.12.4_linux-generic-amd64.tar.xz
解压安装tar文件: tar -xvf wkhtmltox-0.12.4_linux-generic-amd64.tar
将程序拷贝到/usr/bin/目录中,这样可以任意目录执行。
cp wkhtmltox/bin/wkhtmltopdf /usr/bin/
使用Wkhtmltopdf
wkhtmltopdf http://www.baidu.com /data/tmp/demo.pdf
5.如果生成pdf失败,可能是缺少相关的包,进入usr/lib中根据错误信息安装对应的包
cd /usr/lib
[daxiang[@localhost](https://my.oschina.net/u/570656) lib]$ sudo yum install libXrender*
[daxiang[@localhost](https://my.oschina.net/u/570656) lib]$ sudo yum install libXext
JAVA调用Wkhtmltopdf
public class HtmlToPdfUtil {
public static String getCommand(String htmlUrl, String filePath) {
StringBuilder command = new StringBuilder();
String system = System.getProperty("os.name");
if (system.contains("Windows")) {
command.append("D:\\Program Files\\wkhtmltopdf\\bin\\wkhtmltopdf.exe ");
} else if (system.contains("Linux")) {
command.append("wkhtmltopdf ");
}
// command.append("--encoding utf-8 "); //设置文字编码为utf-8
// command.append("--header-center 易观 "); //在页眉中心显示易观
// command.append("--header-line "); //显示一条线在页眉下
// command.append("--margin-left 5cm "); //页面左移5cm
// command.append("--footer-right [page]/[topage] "); //页尾右下角显示页数
command.append(htmlUrl).append(" ").append(filePath);
return command.toString();
}
public static void main(String[] args) throws Exception {
String command = getCommand("https://www.baidu.com/", "e:/demo3.pdf");
Process process = Runtime.getRuntime().exec(command);
process.waitFor(); // 这个调用比较关键,就是等当前命令执行完成后再往下执行
System.out.println("执行完成");
}
}
wkhtmltopdf 中文参数
中文参数详解 :http://blog.csdn.net/zhangkezhi_471885889/article/details/52184744
使用方式:
linux:wkhtmltopdf [OPTIONS]… [More input files]
windows:wkhtmltopdf.exe [OPTIONS]… [More input files]
案例:
wkhtmltopdf --footer-right [page]/[topage] http://www.baidu.com /data/baidu.pdf
wkhtmltopdf --header-center 报表 --outline --header-line --margin-top 2cm http://www.baidu.com /data/baidu.pdf
背景1解决方式
1.建立模板页面: http://localhost:8080/templateView
2.利用wkhtmltopdf生成PDF
注意事项
1.只有通过模板引擎(velocity、Thymeleaf)渲染的web页面才能生成PDF
2.由于命令是通过空格号来识别的,如果生成的PDF文件名中包含空格,会导致生成失败。
知识延伸 (Thymeleaf)
springboot推荐使用Thymeleaf做为模板引擎,以后springboot项目中要用到模板引擎,建议大家都能统一使用Thymeleaf。
springboot配置Thymeleaf:http://blog.didispace.com/springbootweb/
Thymeleaf语法: http://fanlychie.github.io/post/thymeleaf.html#9-3-2-text
到此,关于“HTMl转PDF的方法”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注天达云网站,小编会继续努力为大家带来更多实用的文章!