背景
- 征信查询前置系统查询回客户征信报告后,返回html页面,希望通过接口自动将查回的html文档进行pdf文档的转换,并自动上传至业务系统中,提供前端业务人员进行查看。
方案
- html与pdf的转换采用开源的wkhtmltopdf工具处理,此工具转换效果较号,唯一的缺点就是速度稍慢,可考虑使用多线程方式处理,提升并发效率。
- java程序中使用Runtime来调用操作系统中的命令的方式进行wkhtmltopdf的调用。
代码
class ProcessInputSteramThread implements Runnable{
private InputStream is ;
public ProcessInputSteramThread(InputStream is){
this.is = is ;
}
@Override
public void run() {
byte[] bytes = new byte[1024];
int len = 0 ;
while (true) {
try {
if ((len = is.read(bytes)) != -1){
System.out.println(new String(bytes, 0, len, "gb2312"));
}else {
break ;
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) throws InterruptedException {
Process process = null;
try {
process = Runtime.getRuntime().exec("wkhtmltopdf d:\\123.html d:\\123.pdf");
} catch (IOException e) {
e.printStackTrace();
}
InputStream is = process.getInputStream();
InputStream errIs = process.getErrorStream();
new Thread(new ProcessInputSteramThread(is)).start();
new Thread(new ProcessInputSteramThread(errIs)).start();
process.waitFor();
}
- 总结:
- 1、java的Runtime调用本地的cmd还是非常好用的;
- 2、Rumtime对象exec之后的Process对象的InputStream和ErrorStream都要接收处理;
- 3、wkhtmltopdf工具转换之后的pdf还是非常清晰的,确实速度有些慢。