简体   繁体   中英

pdf created using itext jar giving error(not supported or damaged) at opening ,I am using itext version 5.3.0

Document document = new Document(PageSize.A4, 50, 50, 50, 50);
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("D:/newfile2.pdf"));
document.open();
Anchor anchorTarget = new Anchor("First page of the document.");

anchorTarget.setName("BackToTop");
Paragraph paragraph1 = new Paragraph();

paragraph1.setSpacingBefore(50);

paragraph1.add(anchorTarget);
document.add(paragraph1);

document.add(new Paragraph("Some more text on the \first page with different color and font type.", FontFactory.getFont(FontFactory.COURIER, 14, Font.BOLD, new CMYKColor(0, 255, 0, 0))));

I have tried this, PDF is created but at opening it is showing error also size of file is 0 bytes.

The PdfWriter coupled with a Document stores the page content when the page is finished. A page is finished as soon as either the next page is started or the `Document is closed.

In case of as little content as in the OP's sample on only a single page and without a close call, therefore, it is not surprising that the OP observed that the size of file is 0 byte.

Furthermore each PDF file ends with a special document part containing some document meta data and a cross reference table of the objects in the file. This part also is written when closing the Document .

To make his program produce a valid PDF with the intended contents, therefore, the OP has to eventually close the document:

document.close();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM