iText - 向现有PDF文件添加内容 [英] iText - add content to existing PDF file
问题描述
我想用iText执行以下操作:
I want to do the following with iText:
(1)解析现有PDF文件
(1) parse an existing PDF file
(2)在文档的现有单页上添加一些数据(如时间戳)
(2) add some data to it, on the existing single page of the document (such as a timestamp)
(3)写出文档
我似乎无法弄清楚如何使用iText做到这一点。在伪代码中,我会这样做:
I just can't seem to figure out how to do this with iText. In pseudo code I would do this:
Document document = reader.read(input);
document.add(new Paragraph("my timestamp"));
writer.write(document, output);
但由于某种原因,iText的API非常复杂,我无法理解它。 PdfReader实际上保存文档模型或其他东西(而不是吐出文档),你需要一个PdfWriter来读取它的页面...呃?
But for some reason iText's API is so dauntingly complicated that I can't wrap my head around it. The PdfReader actually holds the document model or something (rather than spitting out a document), and you need a PdfWriter to read pages from it... eh?
推荐答案
iText有多种方法可以做到这一点。 PdfStamper
类是一个选项。但我发现最简单的方法是创建一个新的PDF文档,然后将现有文档中的各个页面导入到新的PDF中。
iText has more than one way of doing this. The PdfStamper
class is one option. But I find the easiest method is to create a new PDF document then import individual pages from the existing document into the new 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
。这些可能是文件流或内存流或任何适合您应用程序的内容。
This will read in a PDF from templateInputStream
and write it out to outputStream
. These might be file streams or memory streams or whatever suits your application.
这篇关于iText - 向现有PDF文件添加内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!