html转换为ofd
首先,html是常见的流式排版文档,而ofd是版式的排版文档,将流式转换为版式(借助于pdf),就需要经历一个转板过程,这个过程有两种方案:
第一步:将html超文本格式转为版式文件,可通过以下两种方案实现:
方案1.人工方式,通过html页面直接Ctrl+P调起打印,输出pdf文件:
private static String toPdfTool = "D:\\wkhtmltopdf\\bin\\wkhtmltopdf.exe";
/**
* html转pdf
* @param srcPath html路径,可以是硬盘上的路径,也可以是网络路径
* @param destPath pdf保存路径
* @return 转换成功返回true
*/
public static boolean convert(int type,String srcPath, String destPath){
File file = new File(destPath);
File parent = file.getParentFile();
//如果pdf保存路径不存在,则创建路径
if(!parent.exists()){
parent.mkdirs();
}
StringBuilder cmd = new StringBuilder();
//非windows 系统
if(System.getProperty("os.name").indexOf("Windows") == -1){
if(type==1){
toPdfTool = "/usr/local/bin/wkhtmltopdf";
cmd.append(toPdfTool);
cmd.append(" ");
cmd.append(" --images");
cmd.append(" --header-line");//页眉下面的线
//cmd.append(" --header-center 这里是页眉这里是页眉这里是页眉这里是页眉 ");//页眉中间内容
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 ");// (设置页眉和内容的距离,默认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 ");// (设置页脚和内容的距离)
cmd.append(" --javascript-delay 2000 ");
cmd.append(" --no-stop-slow-scripts ");
cmd.append(srcPath);
cmd.append(" ");
cmd.append(destPath);
}else{
toPdfTool = "/usr/local/bin/wkhtmltoimage";
cmd.append(toPdfTool);
cmd.append(" ");
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();
proc.waitFor();
}catch(Exception e){
result = false;
e.printStackTrace();
}
return result;
}
通过代码的方案将html渲染后转为pdf的方案。
第二步,版式之间的转换,可以用以下方案:
1.pdf转ofd,通过调用第三方的实现,此处以开源的pdf转换ofd为例,
最终结果