最近项目中用到itext来将html转换为pdf,itext功能确实强大能方便的让您操作pdf文件。同样其对中文也支持的挺好。

  在默认配置情况下,中文是不能显示的或者显示为乱码。为解决此问题,搜遍网络,得出结论是在创建paragrahp时将中文字体传递给pdfdocument。但问题是在项目中需要将html转换为pdf文件,这样创建paragrahp是由html解析器进行处理的,总不能修改itext源代码吧?miciu网站的大大就是用此方案,将itext中3个源代码修改从而保证中文可以显示。

  不过miciu网站大大思路启发了我去研究itext的源代码。使用itext来转换html到pdf时,在新版本中5.4.2中用xmlworker组件是比较明智的选择。通过研究发现itext xmlworker实际提供了某种扩展方式来显示中文,特别是中文默认字体问题。对于没有显示声明css样式的字体,默认使用undefine字体样式,这对于英文是可行的,对于中文来说,这是不可接受的,因此扩展其字体提供方式,让转换器在转换过程中碰到默认字体用宋体来显示,这样就解决了中文不能显示或者乱码的问题。

  具体代码参考如下:

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Font;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.tool.xml.Pipeline;
import com.itextpdf.tool.xml.XMLWorker;
import com.itextpdf.tool.xml.XMLWorkerFontProvider;
import com.itextpdf.tool.xml.XMLWorkerHelper;
import com.itextpdf.tool.xml.exceptions.C***esolverException;
import com.itextpdf.tool.xml.html.CssAppliers;
import com.itextpdf.tool.xml.html.CssAppliersImpl;
import com.itextpdf.tool.xml.html.Tags;
import com.itextpdf.tool.xml.parser.XMLParser;
import com.itextpdf.tool.xml.pipeline.css.C×××esolver;
import com.itextpdf.tool.xml.pipeline.css.C***esolverPipeline;
import com.itextpdf.tool.xml.pipeline.end.PdfWriterPipeline;
import com.itextpdf.tool.xml.pipeline.html.HtmlPipeline;
import com.itextpdf.tool.xml.pipeline.html.HtmlPipelineContext;
public class XMLWorkerDemo {
    public static class MyFontsProvider extends XMLWorkerFontProvider{
        public MyFontsProvider(){
            super(null,null);
        }
        @Override
        public Font getFont(final String fontname, String encoding, float size, final int style) {
                                                                                               
            String fntname = fontname;
            if(fntname==null){
                fntname="宋体";
            }
            return super.getFont(fntname, encoding, size, style);
        }
    }
    private static String dirpath = "";
    public static void main(String[] args) throws FileNotFoundException, IOException, DocumentException, C***esolverException {
        convert2("d:/test0.html","d:/test.pdf");
    }
                                                                                           
    public static void convert2(String infile, String outfile)
            throws FileNotFoundException, IOException, DocumentException,
            C***esolverException {
        Document document = new Document();
        PdfWriter writer = PdfWriter.getInstance(document,
                new FileOutputStream(outfile));
        document.open();
        XMLWorkerDemo.MyFontsProvider fontProvider = new XMLWorkerDemo.MyFontsProvider();
        fontProvider.addFontSubstitute("lowagie", "garamond");
        fontProvider.setUseUnicode(true);
        //使用我们的字体提供器,并将其设置为unicode字体样式
        CssAppliers cssAppliers = new CssAppliersImpl(fontProvider);
        HtmlPipelineContext htmlContext = new HtmlPipelineContext(cssAppliers);
        htmlContext.setTagFactory(Tags.getHtmlTagProcessorFactory());
        C×××esolver c***esolver = XMLWorkerHelper.getInstance()
                .getDefaultC***esolver(true);
        Pipeline<?> pipeline = new C***esolverPipeline(c***esolver,
                new HtmlPipeline(htmlContext, new PdfWriterPipeline(document,
                        writer)));
        XMLWorker worker = new XMLWorker(pipeline, true);
        XMLParser p = new XMLParser(worker);
        File input = new File(infile);
        p.parse(new InputStreamReader(new FileInputStream(input), "UTF-8"));
        document.close();
    }
}

 以上代码能解决大部分中文网页转换为pdf文件的中文不显示或乱码问题,需要注意的是xmlworker只支持xhtml文件即严格意义的html,若是普通html文件,很容易发生异常 no expect tag input等,常见的不封闭的标签有:input、link、metadata、script、p_w_picpath、br等,如何解决html到xhtml或直接使用itext的htmlpareser解决此问题将是后续研究的问题,若有结论,将分享给给位。

 还有个问题需要解决的是对于某些字体itext还是不能很好的处理,我们这边碰到的是楷体,对于楷体转换的pdf文件中还是不能显示对应的中文文字,后面若有解决方案再与诸位分享,若各位有相关的解决方案也请不吝赐教