我试图在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库?我找不到关于这个错误的任何信息。
P.S.:我可以看到错误是与itext而不是itextg有关的,所以我不知道这个事实是否能产生错误。
提前感谢!
发布于 2016-08-08 07:17:10
这是错误的:
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
}在开始自己的实验之前,请仔细阅读文档。您可以在Q&As的快速入门部分找到Hello示例。
实际的问题是,您没有处理try/catch (或throws)的IOException或DocumentException。
您的错误与iText (Java)和iTextG (Android)之间的区别完全无关。您正在使用抛出异常的方法。无论您是在Java还是Android中工作,都需要处理这些异常。
iText与iTextG的差异很小。没有任何理由要有单独的iText和iTextG文档。
https://stackoverflow.com/questions/38822958
复制相似问题