weaver-hrm-salary/src/com/engine/salary/util/pdf/HtmlToPdf.java

79 lines
3.3 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package com.engine.salary.util.pdf;
import com.engine.workflow.biz.requestForm.HtmlToPdfInterceptor;
import lombok.extern.slf4j.Slf4j;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
@Slf4j
public class HtmlToPdf {
/**
* html转pdf
*
* @param toPdfTool 工具路径
* @param srcPath html路径可以是硬盘上的路径也可以是网络路径
* @param destPath pdf保存路径
* @return 转换成功返回true
*/
public static boolean convert(String toPdfTool, String srcPath, String destPath) {
File file = new File(destPath);
File parent = file.getParentFile();
//如果pdf保存路径不存在则创建路径
if (!parent.exists()) {
parent.mkdirs();
}
StringBuilder cmd = new StringBuilder();
cmd.append(toPdfTool);
cmd.append(" ");
cmd.append(" --header-line");//页眉下面的线
cmd.append(" --margin-top 3cm ");//设置页面上边距 (default 10mm)
// cmd.append(" --header-html file:///"+WebUtil.getServletContext().getRealPath("")+FileUtil.convertSystemFilePath("\\style\\pdf\\head.html"));// (添加一个HTML页眉,后面是网址)
cmd.append(" --header-spacing 5 --orientation Portrait ");// (设置页眉和内容的距离,默认0)
//cmd.append(" --footer-center (设置在中心位置的页脚内容)");//设置在中心位置的页脚内容
//cmd.append(" --footer-html file:///"+WebUtil.getServletContext().getRealPath("")+FileUtil.convertSystemFilePath("\\style\\pdf\\foter.html"));// (添加一个HTML页脚,后面是网址)
cmd.append(" --footer-line");//* 显示一条线在页脚内容上)
cmd.append(" --footer-spacing 5 ");// (设置页脚和内容的距离)
//--orientation Portrait --footer-center [page]/[topage] --footer-line
cmd.append(srcPath);
cmd.append(" ");
cmd.append(destPath);
boolean result = true;
try {
Process proc = Runtime.getRuntime().exec(cmd.toString());
HtmlToPdfInterceptor error = new HtmlToPdfInterceptor(proc.getErrorStream());
HtmlToPdfInterceptor output = new HtmlToPdfInterceptor(proc.getInputStream());
error.start();
output.start();
BufferedInputStream err = new BufferedInputStream(proc.getErrorStream());
BufferedReader errBr = new BufferedReader(new InputStreamReader(err));
String lineStr = "";
while ((lineStr = errBr.readLine()) != null) {
//检查命令是否执行失败。
log.info("pdf转换执行中! {}", lineStr);
}
if (proc.waitFor() != 0) {
//p.exitValue()==0表示正常结束1非正常结束
if (proc.exitValue() == 1) {
log.error("pdf转换命令执行失败!");
}
}
} catch (InterruptedException e) {
log.error("pdf转换出错!", e);
e.printStackTrace();
result = false;
} catch (Exception e) {
log.error("pdf转换出错!", e);
result = false;
e.printStackTrace();
}
return result;
}
}