导出PDF ITEXT中文乱码处理

来源:互联网 发布:国内知名早教机构知乎 编辑:程序博客网 时间:2024/05/13 10:26

iText 是利用Java 来操作PDF 操作的一种开源API

简单说明下使用该API创建PDF文件的过程

PS:使用的是iText5.x版本

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/**
     * 创建PDF文件
     * @param filePath  文件路径
     * @param content   需要写入的内容
     * @throws DocumentException
     * @throws IOException
     */
    public void createPdf(String filePath ,String content) throwsDocumentException, IOException{
        //1.创建Document对象
        Document document = new Document();
        FileOutputStream fos = new FileOutputStream(filePath);
        //2.创建一个PdfWriter实例
        PdfWriter.getInstance(document, fos);
        //3.打开文档
        document.open();
        Paragraph graph = new Paragraph(content);
        //4.加入段落
        document.add(graph);
        //5.关闭文档
        document.close();
    }

利用上述程序,运行结果。发现,只有英文部分被写入,中文部分无法被写入。百度得到结论:

需要加入itextasian.jar包,itextasian.jar包有实现了对中文字体的支持。因此加载itextasian.jar到classpath下。

在上述代码中加入如下代码:

?
1
2
3
BaseFont baseFontChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
        Font fontChinese =  new  Font(baseFontChinese , 12 , Font.NORMAL);
        Paragraph graph = new Paragraph(content , fontChinese);

运行,得到如下异常:

Font 'STSong-Light' with 'UniGB-UCS2-H' is not recognized

还是不行,继续研究,在网上前辈们说如下原因:

  iText5.x版本以上中的font和encoding文件都是从String RESOURCE_PATH = "com/itextpdf/text/pdf/fonts/"加载的,而老itextasian.jar的包名是com.lowagie.text.pdf.fonts, 包名不一致导致路径错误,。

具体解决方法就是修改包的路径了,详细方法如下:

1.解压iTextAsian.jar
  得到如下目录:
  iTextAsian
     --com
        --lowagie
          --text
            --pdf
              --fonts
                --...(字体属性文件)
2.将解压后的com目录下的包名lowagie更改为itextpdf
3.在命令行转至iTextAsian目录,重新打包为iTextAsian.jar文件
4.打包命令如下:
  jar cvf iTextAsian.jar com/itextpdf/text/pdf/fonts/*
5.执行后,将新的iTextAsian.jar加入classpath路径

运行结果,OK,解决问题。

最终代码如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/**
     * 创建PDF文件
     * @param filePath  文件路径
     * @param content   需要写入的内容
     * @throws DocumentException
     * @throws IOException
     */
    public void createPdf(String filePath ,String content) throws DocumentException, IOException{
        //1.创建Document对象
        Document document = new Document();
        FileOutputStream fos = new FileOutputStream(filePath);
        //2.创建一个PdfWriter实例
        PdfWriter.getInstance(document, fos);
        //3.打开文档
        document.open();
        BaseFont baseFontChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
        Font fontChinese =  new  Font(baseFontChinese , 12 , Font.NORMAL);
        Paragraph graph = new Paragraph(content , fontChinese);
        document.add(graph);
        document.close();
    }