安卓通过itext创建包含中文的pdf出错

一开始我下载的普通的Itext的jar包,版本是itext-5.5.2.zip。

然后通过正常的代码去创建pdf文件,代码如下:

Document document = new Document();
File mydir = new File(Environment.getExternalStorageDirectory() + "/kutitiku/");
if (!mydir.exists())
    mydir.mkdirs();
String outPath = Environment.getExternalStorageDirectory() + "/kutitiku" + "/mypdf.pdf";
try {
    PdfWriter.getInstance(document, new FileOutputStream(outPath));
    document.open();
    BaseFont bf = null;
    Font fontChinese = null;
    bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
    fontChinese = new Font(bf, 12, Font.NORMAL);
    document.add(new Paragraph("TEST"));
    document.add(new Paragraph(types));
    document.add(new Paragraph("问题", fontChinese));
    document.close();
} catch (DocumentException e1) {
    e1.printStackTrace();
} catch (FileNotFoundException e1) {
    e1.printStackTrace();
} catch (IOException e1) {
    e1.printStackTrace();
}
起初我是通过按照这篇博客的内容做的:

http://www.cnblogs.com/erbin/p/4163108.html

但是后来我发现这篇博客的内容适合与java项目,如果是java项目可以从电脑端加载字体文件,但这个方法不适合与安卓的工程。

后来又找到了这篇文章:

http://blog.csdn.net/nihenbuhao/article/details/42750101

这篇文章的作者将itext-asian.jar和itext.jar进行了打包,里面嵌入了字体文档,这样就可以生成包含中文的pdf文件了。但是项目运行的时候发现会报错:

报错内容如下:Could not find class 'com.itextpdf.awt.PdfPrinterGraphics2D'

去stackoverflow搜了下,是这样解释的:

You've discovered that PdfGraphics2D extends java.awt.Graphics2D, and as you already know Graphics2D is a forbidden class on Android.

You've also encountered problems related to BouncyCastle.

This tells me that you're using the Java version of iText instead of the Android port. In the Android port, we replaced BouncyCastle by SpongyCastle (as recommended when using encryption on Android) and we removed all references to forbidden classes (for instance in the awt and niopackages).

Please switch to using the Android port of iText.

大意是这个itextjar包分为两种,一种是适合与java的,一种是适合与安卓项目的,于是找到了适合于安卓的itextg版本,

可以通过gradle的方式加载这个jar包:

dependencies {

compile 'com.itextpdf:itextg:5.5.9'

}

后来比对了itextg这个jar包,和普通的itext的jar包,发现itextg版本的jar包多了个文件夹:

如图:


将这个mave文件夹拷贝到普通的itext的jar包对应的目录下,再重新打包成jar文件,可以解决这个问题。

现在安卓通过itext生成包含中文的pdf就可以了,正确的jar包链接如下:

http://pan.baidu.com/s/1hsa6iUw

大家可以通过这个链接下载。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值