使用wkhtmltopdf实现HTML转PDF的解决方案
最近,项目需要将HTML页面转换为PDF文件,所以就研究了下HTML转PDF的解决方案,发现网上比较流行的解决方案有3种:
(1)iText
(2)Flying Saucer
(3)wkhtmltopdf
还有一些收费的,我就没测试过了,前两种对HTML的要求过于严格,而且即使你写标准的HTML(当然这都是理想情况下),他也未必可以完美解析,所以我就选择了(3),wkhtmltopdf基于WebKit渲染引擎将HTML内容转换为HTML页面,之后再转换成PDF,所以其转换后的PDF文件的显示效果可以和HTML页面基本保持一致,是一个相当完美的解决方案,美中不足的是他需要你安装插件,并不能像前两种解决方案那样以jar包的形式嵌入到项目中。
因为在使用的过程中,也发现了一些问题,所以就把自己的解决方案写出来,供需要的朋友参考。
CustomWKHtmlToPdfUtil.java是自定义的一个操作wkhtmltopdf的工具类:
package us.kagome.wkhtmltopdf; import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.UUID; /**
* wkhtmltopdf工具类
*
* 约定:
* 1. 插件安装位置,在Windows系统中将插件安装在D盘根目录下(D:/), 在Linux系统中将插件安装在opt目录下(/opt)
*
* 注意:
* 1. wkhtmltopdf的Linux版本中,解压后,默认的文件名为"wkhtmltox",为了统一起见,一律将解压后的文件名,重命名为"wkhtmltopdf"(命令:mv wkhtmltox wkhtmltopdf)
*
* Created by kagome on 2016/7/26.
*/
public class CustomWKHtmlToPdfUtil {
// 临时目录的路径
public static final String TEMP_DIR_PATH = CustomWKHtmlToPdfUtil.class.getResource("/").getPath().substring(1) + "temp/"; static {
// 生成临时目录
new File(TEMP_DIR_PATH).mkdirs();
} public static void main(String[] args) throws Exception {
String htmlStr = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"><html><head><meta http-equiv=\"Content-Type\" content=\"text/html;charset=UTF-8\"></meta><title>HTML转PDF</title></head><body><h1>Hello 世界!</h1></body></html>"; htmlToPdf(strToHtmlFile(htmlStr), TEMP_DIR_PATH + UUID.randomUUID().toString() + ".pdf");
} /**
* 将HTML文件内容输出为PDF文件
*
* @param htmlFilePath HTML文件路径
* @param pdfFilePath PDF文件路径
*/
public static void htmlToPdf(String htmlFilePath, String pdfFilePath) {
try {
Process process = Runtime.getRuntime().exec(getCommand(htmlFilePath, pdfFilePath));
new Thread(new ClearBufferThread(process.getInputStream())).start();
new Thread(new ClearBufferThread(process.getErrorStream())).start();
process.waitFor();
} catch (Exception e) {
throw new RuntimeException(e);
}
} /**
* 将HTML字符串转换为HTML文件
*
* @param htmlStr HTML字符串
* @return HTML文件的绝对路径
*/
public static String strToHtmlFile(String htmlStr) {
OutputStream outputStream = null;
try {
String htmlFilePath = TEMP_DIR_PATH + UUID.randomUUID().toString() + ".html";
outputStream = new FileOutputStream(htmlFilePath);
outputStream.write(htmlStr.getBytes("UTF-8"));
return htmlFilePath;
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
try {
if (outputStream != null) {
outputStream.close();
outputStream = null;
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
} /**
* 获得HTML转PDF的命令语句
*
* @param htmlFilePath HTML文件路径
* @param pdfFilePath PDF文件路径
* @return HTML转PDF的命令语句
*/
private static String getCommand(String htmlFilePath, String pdfFilePath) {
String osName = System.getProperty("os.name");
// Windows
if (osName.startsWith("Windows")) {
return String.format("D:/wkhtmltopdf/bin/wkhtmltopdf.exe %s %s", htmlFilePath, pdfFilePath);
}
// Linux
else {
return String.format("/opt/wkhtmltopdf/bin/wkhtmltopdf %s %s", htmlFilePath, pdfFilePath);
}
} }
ClearBufferThread.java用于清空Process的输入流的缓存的线程类:
package us.kagome.wkhtmltopdf; import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader; /**
* 清理输入流缓存的线程
* Created by kagome on 2016/8/9.
*/
public class ClearBufferThread implements Runnable {
private InputStream inputStream; public ClearBufferThread(InputStream inputStream){
this.inputStream = inputStream;
} public void run() {
try{
BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
while(br.readLine() != null);
} catch(Exception e){
throw new RuntimeException(e);
}
}
}
以上是解决方案的完整代码,接下来说下自己遇到的问题吧!
(1)在jdk1.6环境下,下面代码会造成阻塞:
process.waitFor();
导致程序不能正常执行,jdk1.7就没有这个问题了,去网上找了好久,发现是Process的输入流和错误流缓存不足导致的,所以就增加了ClearBufferThread类用于清空输入流缓存。
使用wkhtmltopdf实现HTML转PDF的解决方案的更多相关文章
- Java操作wkhtmltopdf实现Html转PDF
做java开发的都知道,java生成pdf大部分都是用itext,itext的确是java开源组件的第一选择.不过itext也有局限,就是要自己写模版,系统中的表单数量有好几百个,为每个表单做一个导出 ...
- wkhtmltopdf 将网页转换为PDF和图片
wkhtmltopdf 是一个shell工具,它使用了WebKit渲染引擎和Qt,将网页html转换为pdf的强大工具,转换后的pdf也可以通过pdf工具进行复制.备注.修改 官网下载地址:http: ...
- C# wkhtmltopdf 将html转pdf(详解)
https://www.cnblogs.com/louby/p/905198.html转自,看文章只放了代码看起来云里雾里的,在此做些解析 使用说明: 1.首先呢,得安装下软件,地址下面有链接,文件里 ...
- C# wkhtmltopdf 将html转pdf
一.转换程序代码如下: public string HtmlToPdf(string url) { bool success = true; // string dwbh = url.Split('? ...
- wkhtmltopdf导出html到pdf
1.使用背景 最近公司需要把html页面的内容生成pdf并下载,试过很多方法都没有满意的效果,后来找到wkhtmltopdf这款软件,终于解决了这个问题. wkhtmltopdf是exe文件, ...
- wkhtmltopdf cpdf HTML转pdf 及pdf合并
将 html 转为 pdf :wkhtmltopdf wkhtmltopdf 是一个使用 webkit 网页渲染引擎开发的用来将 html 转成 pdf 的工具,可以跟多种脚本语言进行集成来转换文档. ...
- Web方式预览Office/Word/Excel/pdf文件解决方案
最近在做项目时需要在Web端预览一些Office文件,经过在万能的互联网上一番搜索确定并解决了. 虽然其中碰到的一些问题已经通过搜索和自己研究解决了,但是觉得有必要将整个过程记录下来,以方便自己以后查 ...
- wkhtmltopdf 将网页生成pdf文件
先安装依赖 yum install fontconfig libXrender libXext xorg-x11-fonts-Type1 xorg-x11-fonts-75dpi freetype l ...
- 使用com.aspose.words将word模板转为PDF乱码解决方案(window下正常)
最近在做电子签名过程中,需要将合成的电子签名的word文件(正常)转换为pdf文件时,在开发平台window下转换没有问题,中文也不会出现乱码.但是将项目部署到正式服务器(Linux)上,转换出来的p ...
随机推荐
- C++中getline被跳过
#include "stdafx.h" #include"iostream" #include"math.h" #include" ...
- appium跑demo简单实例讲解
安装appium,设置 demo.pyfrom appium import webdriver #要装webdriver,方法查看http://www.cnblogs.com/sincoolvip/p ...
- 在使用easyui,datagrid时,JSON中的如果含有换行符,则不能显示数据
http://www.xuebuyuan.com/2103538.html 每项值需处理换行符 item = item.Replace("\r\n", ""); ...
- 求任意长度数组的最大值(整数类型)。利用params参数实现任意长度的改变。
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.T ...
- 织梦DedeCms去掉栏目页面包屑导航最后的分隔符“>”
织梦DedeCms的面包屑导航调用标签{dede:field name=’position’ /},在栏目页里调用的面包屑导航,最后会出现分割符号“>”,如:主页 > DedeCms 模板 ...
- (翻译)初学者的object-C指南
初学者的object-C指南 英文原文:http://blog.teamtreehouse.com/the-beginners-guide-to-objective-c-language-and-va ...
- squid 学习笔记
Squid学习笔记 1.安装前的配置 编译安装之前需要校正的参数主要包括File Descriptor和Mbuf Clusters. 1.File Descriptor 查看文件描述符的限制数目: u ...
- 搭建SpringMVC+Mybatis框架并实现数据库的操作
User类 public class User { private Integer id; private String userName; private String password; priv ...
- HTML常见标签总结
什么是浏览器 解释和执行HTML源码的工具 五大浏览器:IE.FF(FireFox)(火狐).Chrome(谷歌).Opera(空中).Safari(Apple)(苹果) IE用的是Trident引擎 ...
- ldconfig deferred processing now taking place
在ubuntu下面安装软件,安装结束后,提示:ldconfig deferred processing now taking place 到网上查询了一下,大概意思是说:软件安装完了,是否要重启电脑.