/** * AsianTest.java */import java.io.FileOutputStream;import java.io.IOException;import com.lowagie.text.*;import com.lowagie.text.pd
最近在项目需要,需要将html内容转换成pdf的文件,采用itextpdf总是不显示中文。
找了很多方法都没搞定,然后在网上看到了有个帖子说改源码解决这个问题,前面的文章《使用itext将html生成pdf中文换行问题解决方案》是使用itext2.0.8版本实现,这里使用itext5.4.2实现,这里用到了itext-asian.jar和xmlworker-5.4.2.j但是经过测试还是没有搞定。
并且个人不建议改源码,然后自己研究源码,借鉴了他的思路,可以不用改源码即可解决中文问题。
第一部:
maven 引入依赖的jar包
com.itextpdf
itextpdf
5.5.9
com.itextpdf.tool
xmlworker
5.5.9
com.itextpdf
itext-asian
5.2.0
根据ChunkCssApplier重写apply方法
@SuppressWarnings("deprecation")
public class MyChunkCssApplier extends ChunkCssApplier {
public static BaseFont chinessFont = null;
static {
try {
// 中文支持,需要引入 itext-asian.jar
chinessFont = BaseFont.createFont("STSongStd-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 判断是否存在中文
* @param str
* @return
*/
private static boolean isChinese(String str){
if(str == null ){
return false;
}
//存在中文
String regex = ".*[\\u4e00-\\u9faf].*";
return Pattern.matches(regex, str);
}
/**
*
* 重写apply方法
*/
@Override
public Chunk apply(Chunk c, Tag t) {
Font f = applyFontStyles(t);
// 增加此段代码 如果中文 ,则返回中文字体
if (null != chinessFont && isChinese(c