0

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

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 库?我找不到有关此错误的任何信息。

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

提前致谢!

4

1 回答 1

1

这是错误的:

PdfDocument pdf = new PdfDocument();

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

像这样调整您的代码:

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
}

在开始自己进行实验之前,请仔细阅读文档。您可以在问答的入门部分找到一个 Hello World 示例。

实际问题是由于您没有处理 an或 a的try/ catch(或 a )造成的。throwsIOExceptionDocumentException

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

iText 和 iTextG 之间几乎没有区别。没有任何理由拥有单独的 iText 和 iTextG 文档。

于 2016-08-08T07:17:10.517 回答