java实现html带样式转pdf
做项目偶遇html版征信报告转pdf存储
查阅各博主方案有的是不支持样式,有的是过于繁琐,今天分享一个比较简单有效的方法 windows liunx 亲测有效
首先需要下载插件 分为windows版本和 liunx版本
百度网盘:https://pan.baidu.com/s/1yFvNULcmbmAYII7Vn0ZBpw
提取码:3660
以windows为例
打开cmd执行命令
C:\Users\Administrator/tmp/src/wkhtmltox/bin/wkhtmltopdf --enable-local-file-access C:\Users\Administrator\tmp\src\html\html\2162537843264761856618949.html C:\Users\Administrator\tmp\src\html\html\2162537843264761856618949.pdf
如图,界面打印Done时执行完成,查看生成pdf
打开pdf 支持任意页数,包含样式
下面讲述下java实现过程
public Boolean htmlToPdf(String htmlFile,String pdfFile){
try {
String cmd = Constants.LOCAL_PATH + PLUGINSPATH + htmlFile +" "+ pdfFile;
log.info("=================>脚本:{}",cmd);
Process exeEcho = Runtime.getRuntime().exec(cmd);
BufferedReader reader = new BufferedReader(new InputStreamReader(exeEcho.getErrorStream()));
String line = null;
while ((line = reader.readLine()) != null) {
if ("Done".equals(line)){
break;
}
}
log.info("文件上传或下载成功");
return true;
}catch (Exception e){
log.info("文件解析异常");
throw new BizException(ErrCode.E100132);
}
}
代码中
if ("Done".equals(line)){
break;
}
监听pdf生成是否完成,如果在不监听的情况下,存在异步,可以读取文件查看,可能会报空指针异常。