我想用 iText 做以下事情:
(1) 解析现有的 PDF 文件
(2) 在文档的现有单页上添加一些数据(例如时间戳)
(3) 写出文件
我似乎无法弄清楚如何使用 iText 执行此操作。在伪代码中我会这样做:
Document document = reader.read(input);
document.add(new Paragraph("my timestamp"));
writer.write(document, output);
但由于某种原因,iText 的 API 非常复杂,以至于我无法理解它。 PdfReader 实际上保存了文档模型或其他东西(而不是吐出文档),您需要一个 PdfWriter 来从中读取页面......嗯?
最佳答案
iText 有不止一种方法可以做到这一点。 PdfStamper
类是一种选择。但我发现最简单的方法是创建一个新的 PDF 文档,然后将现有文档中的各个页面导入到新的 PDF 中。
// Create output PDF
Document document = new Document(PageSize.A4);
PdfWriter writer = PdfWriter.getInstance(document, outputStream);
document.open();
PdfContentByte cb = writer.getDirectContent();
// Load existing PDF
PdfReader reader = new PdfReader(templateInputStream);
PdfImportedPage page = writer.getImportedPage(reader, 1);
// Copy first page of existing PDF into output PDF
document.newPage();
cb.addTemplate(page, 0, 0);
// Add your new data / text here
// for example...
document.add(new Paragraph("my timestamp"));
document.close();
这将从 templateInputStream
读取 PDF 并将其写入 outputStream
。这些可能是文件流或内存流或适合您的应用程序的任何内容。
关于java - iText - 将内容添加到现有的 PDF 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3335126/