我有一个关于 itextpdf 的问题。
private void generatePdf() throws Exception {
FileOutputStream fos = null;
try {
PdfReader reader = new PdfReader("template.pdf");
fos = new FileOutputStream("test.pdf");
PdfStamper stamper = new PdfStamper(reader, fos);
stamper.close();
} catch (Exception e) {
throw e;
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
throw new Exception(e);
}
}
}
}
此方法必须读取模板并将其保存到新的 pdf 中。但如果我查看结果 pdf,我只会看到空白页(4 - 与模板的数量相同)。 有趣的是,这个方法是在 jboss 服务器上的 Web 应用程序上下文中调用的。但是当我在简单的java应用程序(带有main()方法的类)中像main方法一样调用这个方法时,它工作得很好。 另外,我可以添加什么,模板具有将来必须填写的可编辑字段,但现在没有任何编辑。 有人能假设这里可能出了什么问题吗?
最诚挚的问候, 谢尔盖
最佳答案
原因
在评论中,OP 在 Maven 中创建了他的 Web 应用程序,template.pdf
文件作为 Maven 资源提供,并且激活了资源的过滤(即文本变量替换)。
但不幸的是,过滤资源意味着资源文件将被视为最终使用 UTF-8 字符编码存储的文本文件。
这基本上破坏了所有压缩流内容(尤其是页面内容和字体程序)和一些元信息字符串,并且还导致交叉引用不正确(写入为 UTF-8 引入了偏移偏移量的额外字节)。
在为损坏的文件创建交叉引用表后,iText 仍然可以读取 PDF,因为在这些流和字符串之外,结构仍然是正确的。因此,写入读取的损坏的 PDF 的结果包含正确的页数和一些表单字段,但页面内容丢失了。
治疗方法
解决方案是不过滤PDF资源。这可以例如按照说明进行 here在 Apache Maven 站点上:
By default, files with extensions (jpg, jpeg, gif, bmp and png) won't be filtered anymore.
Users can add some extra file extensions to not apply filtering with the following configuration :
<project> ... <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-resources-plugin</artifactId> <version>2.7</version> <configuration> ... <nonFilteredFileExtensions> <nonFilteredFileExtension>pdf</nonFilteredFileExtension> <nonFilteredFileExtension>swf</nonFilteredFileExtension> </nonFilteredFileExtensions> ... </configuration> </plugin> </plugins> ... </build> ... </project>
关于java - Itextpdf停止正确转换pdf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28898636/