原项目中有在使用flying-saucer库来生成pdf,奈何不支持css3样式,然后遇到一个需求,客户要求设置透明度,然而百度一波,发现rgba 和 Opacity都是css3的,我当即就说这功能做不了。
说是说了,做还是得做,面向百度搜索了一波,发现了WKHtmlToPdf程序,于是开始安装
环境:centos7 x86_64
- wget https://github.com/wkhtmltopdf/packaging/releases/download/0.12.6-1/wkhtmltox-0.12.6-1.centos7.x86_64.rpm
其他版本看这里 - rpm2cpio wkhtmltox-0.12.6-1.centos7.x86_64.rpm | cpio -di
- yum install libXrender*
yum install libfontconfig*
yum install libXext* - wkhtmltopdf.exe 1234.html ./1234.pdf
生成成功,
5. 设置环境变量
WKHTMLTOPDF_HOME=/data/usr/local/bin
6. 开始编码
public File htmlToPdfWKHtmlToPdf(String template, Map<String, Object> map) {
Context context = new Context();
context.setVariables(map);
templateEngine.process(template, context);
// 转义字符
htmlcontext = htmlcontext.replaceAll("<", "<").replaceAll(">", ">");
// 创建临时文件
FileUtils.fileWriteOut(htmlcontext.getBytes(), filePath, htmlFile);
if (!flag) {
throw new ServiceException("html文件写入硬盘失败!");
}
// 生成pdf
String fullHtmlPath = filePath + "/" + htmlFile;
boolean convert = convert(fullHtmlPath, fullPdfFile);
if (!convert) {
throw new ServiceException("html文件转换成pdf文件过程失败");
}
return new File(fullPdfFile);
}
public static boolean convert(String srcPath, String destPath) {
File file = new File(destPath);
File parent = file.getParentFile();
// 如果pdf保存路径不存在,则创建路径
if (!parent.exists()) {
parent.mkdirs();
}
StringBuilder cmd = new StringBuilder();
// 获取环境变量
String env = System.getenv(WKHTMLTOPDF_HOME);
if (StringUtils.isEmpty(env)) {
throw new ServiceException("环境变量{0}没有设置", WKHTMLTOPDF_HOME);
}
cmd.append(env);
String os = System.getProperties().getProperty("os.name");
if (os != null && os.toLowerCase().indexOf("linux") > -1) {
cmd.append("/wkhtmltopdf");
} else {
cmd.append("/wkhtmltopdf.exe");
}
cmd.append(" ");
cmd.append(srcPath);
cmd.append(" ");
cmd.append(destPath);
boolean result = true;
try {
Process proc = Runtime.getRuntime().exec(cmd.toString());
proc.waitFor();
} catch (Exception e) {
result = false;
e.printStackTrace();
}
return result;
}
参考链接:
https://www.cnblogs.com/IT-study/p/13706690.html