iText-将内容添加到现有的PDF文件

我想对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();

它将从中读取PDFtemplateInputStream并将其写入outputStream。这些可能是文件流或内存流,或任何适合您的应用程序的流。

以上是 iText-将内容添加到现有的PDF文件 的全部内容, 来源链接: utcz.com/qa/430363.html

回到顶部