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根目錄下