需要用到的包core-renderer.jar iText-2.0.8.jar iTextAsian.jar simsun.ttc
核心方法如下
/**
* html转pdf
* @param htmlStr
* @param pdfPath
* @return
* @throws Exception
*/
public static String htmlToPdf(String htmlStr,String pdfPath) throws Exception{
ITextRenderer render = new ITextRenderer();
ITextFontResolver font = render.getFontResolver();
try{
String fontPath =Template.class.getResource("simsun.ttc").getPath();//中文字体文件路径
font.addFont(fontPath, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
OutputStream out = new FileOutputStream(new File(pdfPath));
render.setDocumentFromString(htmlStr);
//render.getSharedContext().setBaseURL("file:"+File.separator + basePath+File.separator+"clmNotice"+File.separator);//设置图片路径
render.layout();
render.createPDF(out);
out.flush();
out.close();
}catch (Exception e) {
throw e;
// TODO: handle exception
}
return pdfPath;
}
public static void main(String[] args) {
String str="<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"> <html xmlns=\"http://www.w3.org/1999/xhtml\" ><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\"/><style type=\"text/css\" mce_bogus=\"1\">body{font-family: SimSun; }#baseInfoMenu li{ list-style: none; float:left; padding-right:5px; margin-left:10px }</style><title>电子照会 </title></head> <body><div style=\"width:97%;align:center\"><div align=\"center\"> <h1 align=\"center\">电子照会</h1></div> <ul id=\"baseInfoMenu\"> <li>保单号: 00158935</li><li >受理号:1069081</li><li>投保人:null</li><li>被保险人:汪思明 </li> </ul><br/> <table> <tr ><td align=\"center\"><h2>一般照会:<font style=\"color: red\">(1)</font></h2></td></tr> <tr><td> 累计寿险与意外险保险金额之和超过人民币100万,请提供财务证明包括:个人资产证明、企业法人营业执照等。 </td></tr> </table> <hr/> <table> <tr ><td align=\"center\"><h2>体检原因:<font style=\"color: red\">(1)</font></h2></td></tr> <tr><td> 寿险累计保额超过免体检额度(岁/万) </td></tr> </table> <hr/> <table> <tr ><td align=\"center\"><h2>体检项目:<font style=\"color: red\">(12)</font></h2></td></tr> <tr><td> 血检:肝功能 </td></tr> <tr><td> 血检:乙肝表面抗原 </td></tr> <tr><td> 血检:特别血液检查(BTX) </td></tr> <tr><td> 血检:血脂检测(项目:总胆固醇、甘油三脂、高密度脂蛋白、低密度脂蛋白、极低密度脂蛋白)〈空腹〉 </td></tr> <tr><td> 血检:空腹血糖〈请空腹8小时以上〉 </td></tr> <tr><td> 腹部B超(双肾、输尿管、膀胱) </td></tr> <tr><td> 腹部B超(肝、胆、胰、脾、女性加做妇科B超) 〈请空腹8小时以上〉 </td></tr> <tr><td> 血检:血常规 </td></tr> <tr><td> 静止心电图 </td></tr> <tr><td> 胸部X光拍片检查 </td></tr> <tr><td> 显微镜尿液分析 </td></tr> <tr><td> 一般体检 </td></tr> </table> <hr/> <table> <tr ><td align=\"center\"><h2>AWU补充告知申明书:<font style=\"color: red\">(2)</font></h2></td></tr> <tr><td> 信诚慧选投资连结保险累计年缴化保费已超过本公司规定的最高保费6000元,请重新确认投保计划及保费。 </td></tr> <tr><td> 同一被保险人所有生效的慧选投连险的主合同年缴保费累计不能超过4800元,请客户重新确认保险计划。 </td></tr> </table> <hr/> <table> <tr><td colspan=\"2\"> <b>照会回复栏:</b></td></tr> <tr> <td> 惯用选项:不同意<br/>回复:11 </td> </tr> </table> </div></body></html>";
try {
htmlToPdf(str,"D:\\测试时中.pdf");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}