itext html 中文

最近做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;
   }
 } 
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值