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

Why this error occurs: Unhandled exception: com.itextpdf.text.DocumentException on Android?

我正在尝试在 Android 上创建 PDF,但仅在按下按钮时显示一些信息,而不是将其存储在移动设备上 phone。我收到此错误:

Unhandled exception: com.itextpdf.text.DocumentException

但我不明白为什么会这样。我有以下代码:

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 有关,所以我不知道是否这个事实可能会产生错误。

提前致谢!

这是错误的:

PdfDocument pdf = new PdfDocument();

在 iText 5 中,PdfDocument 是 class 仅供 iText 内部使用。您应该改用 Document class。

像这样调整您的代码:

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
}

请阅读问答的 documentation carefully before starting to experiment on your own. You can find a Hello World example in the Getting Started 部分。

实际问题是由于您没有 try/catch(或 throws)来处理 IOExceptionDocumentException.

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

中工作

iText 和 iTextG 之间的区别很小。没有任何理由需要单独的 iText 和 iTextG 文档。