iText - adding Image element generates a corrupt PDF file

倾然丶 夕夏残阳落幕 提交于 2019-12-11 23:18:35

问题


I'm using iText® 5.2.1 ©2000-2012 1T3XT BVBA and Integration Designer 8.0 to create a PDF file that is exported in an byte array.

I am creating a document with a fair amount of text and want to add a logo at the beginning.

Part of the code that is adding the image is as follows:

BASE64Decoder decoder = new BASE64Decoder();
byte[] decodedBytes = decoder.decodeBuffer(Stringovi.SLIKA1);
Image image1 = Image.getInstance(decodedBytes);
image1.setAbsolutePosition(30f, 770f);
image1.scalePercent(60f);
document.add(image1);

The input image is in byte array format because of the system requirements. The rest of the document consists of different tables with various content and it's all text. When I add the image in the before mentioned way the program finishes and i get an byte output that i run trough a Base64 decoder. Resulting PDF can not be opend and the error shown is:

 "Error [PDF Structure 40]:Invalid reference table (xref)"

I can't see where my mistake is so if anybody could be so kind and point me in the right direction I would very much appreciate it.


回答1:


The document you presented as a "broken PDF file" is not a complete PDF file. It doesn't end with %%EOF, it doesn't have a cross-reference table,... It's a PDF document that isn't complete.

This means that you don't have the following line in your code:

document.close();

If you do have this line, it isn't reached. For instance: an exception is thrown causing the code to jump to a catch clause, skipping the close() operation.

The error message saying Invalid reference table (xref) is consistent with that diagnosis. This isn't a problem caused by iText. It's a problem caused by bad coding: not closing the document and/or not dealing with exceptions correctly.



来源:https://stackoverflow.com/questions/24265588/itext-adding-image-element-generates-a-corrupt-pdf-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!