背景公司一些数据需要提供给第三方看,不能让第三方更改,生成pdf格式的文件是个不错的选择,pdf繁琐至极,好在有大神写好的库,它就是wkhtmltopdf
使用[h1]下载[/h1]下载地址
[h1]cmd命令体验[/h1]- exe位置 html位置 生成pdf位置wkhtmltopdf.exe F:/htmltopdf/test.html test.pdf
复制代码![]()
[h1]代码[/h1]- /** * html转pdf * @param exePath exe路径 * @param srcPath html路径 * @param destPath pdf路径 * @return 转换成功返回true */ public static boolean convert(String exePath, String srcPath, String destPath) { File file = new File(destPath); File parent = file.getParentFile(); //如果pdf保存路径不存在,则创建路径 if (!parent.exists()) { parent.mkdirs(); } StringBuilder cmd = new StringBuilder() .append(exePath) .append(" ") .append(srcPath) .append(" ") .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; log.error("生成pdf出错", e); } return result; } public static void writeFileByBytes(String content, String fileName) { //以字节为单位写入文件 File file = new File(fileName); //创建一个文件 OutputStream out = null; try { out = new FileOutputStream(file); //打开文件输出流 byte[] bytes = content.getBytes(); //读取输出流中的字节 out.write(bytes); //写入文件 log.info("写文件{} 成功!", file.getAbsolutePath()); System.out.println(); } catch (IOException e) { log.info("写文件{} 失败!", file.getAbsolutePath()); e.printStackTrace(); } finally { if (out != null) { try { out.close(); //关闭输出文件流 } catch (IOException el) { log.error("关闭输出文件流 error", el); } } } }public class HtmlToPdfInterceptor extends Thread { private InputStream is; public HtmlToPdfInterceptor(InputStream is){ this.is = is; } public void run(){ try{ InputStreamReader isr = new InputStreamReader(is, "utf-8"); BufferedReader br = new BufferedReader(isr); String line = null; while ((line = br.readLine()) != null) { System.out.println(line.toString()); //输出内容 } }catch (IOException e){ e.printStackTrace(); } }}
复制代码 [h1]效果[/h1]![]()
|
|