最近做pdf显示,用itext转换html,百度google 不是版本太老,就是没有直白的方案,记录下解决方案
需要
itext-asian.jar 字体相关
itextpdf-5.5.3.jar
xmlworker-5.5.3.jar
包 百度 谷歌之
package com.padf.lib; /** * @author */ import java.io.ByteArrayInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.nio.charset.Charset; import com.itextpdf.text.BaseColor; import com.itextpdf.text.Document; import com.itextpdf.text.DocumentException; import com.itextpdf.text.Font; import com.itextpdf.text.FontProvider; import com.itextpdf.text.pdf.BaseFont; import com.itextpdf.text.pdf.PdfWriter; import com.itextpdf.tool.xml.XMLWorkerHelper; public class PdfTest { public static void main(String[] args) { try { Document document = new Document(); PdfWriter mPdfWriter = PdfWriter. getInstance(document, new FileOutputStream("F:\\test2.pdf" )); document.open(); String s=getHtml(); ByteArrayInputStream bin = new ByteArrayInputStream(s.getBytes()); XMLWorkerHelper.getInstance().parseXHtml(mPdfWriter, document, bin, null,new ChinaFontProvide()); document.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (DocumentException e) { e.printStackTrace(); }catch (Exception e) { e.printStackTrace(); } } public static String getHtml(){ StringBuffer html = new StringBuffer(); html.append("<h1>标题</h1>"); html.append("<table>"); html.append("<tr>"); html.append("<th>xx</th>"); html.append("</tr>"); for (int i=0;i<3;i++) { html.append("<tr>"); html.append("<td>xxx中文</td>"); html.append("</tr>"); } html.append("</table>"); return html.toString(); } /** * * 提供中文 * */ public static final class ChinaFontProvide implements FontProvider{ @Override public Font getFont(String arg0, String arg1, boolean arg2, float arg3, int arg4, BaseColor arg5) { BaseFont bfChinese =null; try { bfChinese=BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED); } catch (Exception e) { e.printStackTrace(); } Font FontChinese = new Font(bfChinese, 12, Font.NORMAL); return FontChinese; } @Override public boolean isRegistered(String arg0) { return false; } } }