且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-06-24 08:29:07

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.