使用freemarker和itext把html转pdf
1.把html转pdf,首先必须要解决中文显示问题,CSS样式问题以及可能的JS问题,先上例子,自己去体会。
2.先去下载simsun.ttc字体;
2.demo.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF8"/> <title>Title</title> <style> .color { color: green; } .pos { position: absolute; left: 200px; top: 5px; width: 200px; fontsize: 10px; } </style> </head> <body style="font-family: SimSun"> <img src="logo.png" width="600px" /> <div class="color pos"> hello,${name}; </div> </body> </html>
3.java实现转换代码
package com.ra.truck.createpdf; import com.itextpdf.text.pdf.BaseFont; import com.lowagie.text.*; import com.lowagie.text.Font; import com.lowagie.text.Rectangle; import com.lowagie.text.pdf.PdfWriter; import freemarker.template.Configuration; import freemarker.template.Template; import org.xhtmlrenderer.pdf.ITextFontResolver; import org.xhtmlrenderer.pdf.ITextRenderer; import java.awt.*; import java.io.*; import java.util.HashMap; import java.util.Map; /** * @Auther: lanhao * @Date: 2018/8/7 11:46 * @Description: */ public class JavaToPdfHtmlFreeMarkerFS { private static final String DEST ="../HelloWorld_CN_HTML_FREEMARKER_FS_index.pdf"; private static final String HTML = "demo.html"; private static final String FONT = "simsun.ttc";private static final String LOGO_PATH ="file:/"+PathUtil.getCurrentPath()+"/"+"demo448"+".png"; private static Configuration freemarkerCfg=null; static { freemarkerCfg =new Configuration(); //freemarker的模板目录 try { freemarkerCfg.setDirectoryForTemplateLoading(new File(PathUtil.getCurrentPath())); } catch (IOException e) { e.printStackTrace(); } } public static void main(String[] args){ String os=System.getProperty("os.name"); System.out.println(os); Map<String,Object> data = new HashMap<>(); data.put("name","lan浩"); String content =freeMarkerRender(data,HTML); createPdf(content,DEST); } /** * freemarker渲染html */ public static String freeMarkerRender(Map<String, Object> data,String htmlTmp) { Writer out = new StringWriter(); try { // 获取模板,并设置编码方式 Template template = freemarkerCfg.getTemplate(htmlTmp); template.setEncoding("UTF8"); // 合并数据模型与模板 template.process(data, out); //将合并后的数据和模板写入到流中,这里使用的字符流 out.flush(); return out.toString(); } catch (Exception e) { e.printStackTrace(); } finally { try { out.close(); } catch (IOException ex) { ex.printStackTrace(); } } return null; } private static void createPdf(String content,String dest) { try { ITextRenderer render = new ITextRenderer(); //解决中文不显式问题 ITextFontResolver fontResolver = render.getFontResolver(); fontResolver.addFont(FONT,BaseFont.IDENTITY_H,BaseFont.NOT_EMBEDDED); // 解析html生成pdf render.setDocumentFromString(content); //解决图片相对路径的问题 render.getSharedContext().setBaseURL(LOGO_PATH); render.layout(); render.createPDF(new FileOutputStream(dest)); }catch (Exception e) { e.printStackTrace(); } } }
注:引用的文件全部放在项目的resource根目录下