首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为什么会出现此错误:未处理的异常:安卓上的com.itextpdf.text.DocumentException?

为什么会出现此错误:未处理的异常:安卓上的com.itextpdf.text.DocumentException?
EN

Stack Overflow用户
提问于 2016-08-08 06:57:13
回答 1查看 2.2K关注 0票数 0

我试图在Android上创建一个PDF格式,但我只想在按下按钮时显示一些信息,而不是把它存储在手机上。我得到了这个错误:

代码语言:javascript
复制
Unhandled exception: com.itextpdf.text.DocumentException

但我不明白为什么会发生这种情况。我有以下代码:

代码语言:javascript
复制
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PdfDocument pdf = new PdfDocument();

PdfWriter pdfWriter = PdfWriter.getInstance(pdf, baos); //Error here
pdf.open();
pdf.add(new Paragraph("Hello world")); //Error here
pdf.close();

byte[] pdfByteArray = baos.toByteArray();

我为什么要犯这个错误?我是否不正确地使用itextg库?我找不到关于这个错误的任何信息。

P.S.:我可以看到错误是与itext而不是itextg有关的,所以我不知道这个事实是否能产生错误。

提前感谢!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-08-08 07:17:10

这是错误的:

代码语言:javascript
复制
PdfDocument pdf = new PdfDocument();

在iText 5中,PdfDocument是一个仅供iText在内部使用的类。您应该使用Document类来代替。

对代码进行如下调整:

代码语言:javascript
复制
try {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    Document document = new Document();
    PdfWriter pdfWriter = PdfWriter.getInstance(document, baos); //Error here
    document.open();
    document.add(new Paragraph("Hello world")); //Error here
    document.close();
    byte[] pdfByteArray = baos.toByteArray();
}
catch (DocumentException de) {
    // handle the exception when something goes wrong on the iText level.
    // for instance: you add one element to another element that is incompatible
}
catch (IOException) {
    // handle the exception when something goes wrong on the IO level.
    // for instance: you try to write to a file in a folder that doesn't exist
}

在开始自己的实验之前,请仔细阅读文档。您可以在Q&As的快速入门部分找到Hello示例。

实际的问题是,您没有处理try/catch (或throws)的IOExceptionDocumentException

您的错误与iText (Java)和iTextG (Android)之间的区别完全无关。您正在使用抛出异常的方法。无论您是在Java还是Android中工作,都需要处理这些异常。

iText与iTextG的差异很小。没有任何理由要有单独的iText和iTextG文档。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/38822958

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档