JAVA 通过 itext,wkhtmltopdf 等,将 HTML 转成 PDF。 这里通过 wkhtmltopdf 实现htmlHTML转PDF
wkhtmltopdf 是一个开源的,使用Qt WebKit 渲染引擎,把 html 转换为 pdf 文件的命令行工具。
wkhtmltopdf官网地址
wkhtmltopdf
下载
下载地址:https://wkhtmltopdf.org/downloads.html根据系统选择相应的版本 这里以Linux为例: 版本:wkhtmltox-0.12.6-1.centos7.x86_64.rpm
安装
- 上传rpm文件到安装目录 /usr/local
cd /usr/local
- 安装 rpm
rpm -ivh wkhtmltox-0.12.6-1.centos7.x86_64.rpm
- 查看安装路径
whereis wkhtmltopdf
- 字体安装(Linux)
将 simsum.ttc 字体上传至 /usr/share/fonts/chinese/TrueType 注:没有该路径就 mkdir 创建,字体也可以去windows系统 C:\Windows\Fonts 目录下找
卸载
rpm -qa |grep wkhtmlto
rpm -e wkhtmltox-0.12.6-1.centos7.x86_64
wkhtmltopdf自动生成文档
方式一:通过wkhtmltopdf -H查看自动生成文档
wkhtmltopdf -H
方式二:访问官方查看自动生成文档 https://wkhtmltopdf.org/usage/wkhtmltopdf.txt
JAVA集成wkhtmltopdf
HtmlToPdf拦截器
public class HtmlToPdfInterceptor extends Thread {
private InputStream inputStream;
public HtmlToPdfInterceptor(InputStream is){
this.inputStream = inputStream;
}
public void run(){
InputStreamReader inputStreamReader = null;
BufferedReader bufferedReader = null;
try{
inputStreamReader = new InputStreamReader(inputStream, "utf-8");
bufferedReader = new BufferedReader(inputStreamReader);
String line = null;
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line.toString());
}
}catch (IOException e){
e.printStackTrace();
}finally {
try{
if(null != inputStreamReader){
inputStreamReader.close();
}
if(null != bufferedReader){
bufferedReader.close();
}
}catch (IOException e){
e.printStackTrace();
}
}
}
}
wkhtmlltopdf操作类
public class HtmlToPdfOperator {
public void convert(String fromPath, String toPath){
File file = new File(toPath);
File parent = file.getParentFile();
if(!parent.exists()){
parent.mkdirs();
}
StringBuilder cmd = new StringBuilder();
cmd.append(getWkhtmltopdfPath());
cmd.append(" --print-media-type");
cmd.append(" --page-size A4");
cmd.append(" --page-width 270mm");
cmd.append(" --page-height 382mm");
cmd.append(" ");
cmd.append(fromPath);
cmd.append(" ");
cmd.append(toPath);
try{
Process proc = Runtime.getRuntime().exec(cmd.toString());
HtmlToPdfInterceptor error = new HtmlToPdfInterceptor(proc.getErrorStream());
HtmlToPdfInterceptor output = new HtmlToPdfInterceptor(proc.getInputStream());
error.start();
output.start();
proc.waitFor();
}catch(Exception e){
e.printStackTrace();
}
}
private String getWkhtmltopdfPath() {
String wkhtmltopdfPath = "D:\\applocation\\wkhtmltopdf\\bin\\wkhtmltopdf.exe";
return wkhtmltopdfPath;
}
}
|