pdf 使用 itext jar 创建,在打开时给出错误(不支持或损坏),我使用的是 itext 版本 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))));

我已经尝试过这个,PDF 已创建,但在打开时显示错误,文件大小也为 0 字节。

PdfWriterDocument相结合,在页面完成时存储页面内容。一旦下一页开始或"文档"关闭,页面就完成了。

因此,如果 OP 示例中的内容与单个页面上的内容一样少,并且没有close调用,则 OP 观察到文件大小为 0 字节也就不足为奇了。

此外,每个PDF文件都以一个特殊的文档部分结尾,其中包含一些文档元数据和文件中对象的交叉引用表。这部分也是在关闭Document时写的。

因此,为了使他的程序生成具有预期内容的有效PDF,OP最终必须关闭文档:

document.close();

最新更新