Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iText - add content to existing PDF file

Tags:

java

pdf

itext

I want to do the following with iText:

(1) parse an existing PDF file

(2) add some data to it, on the existing single page of the document (such as a timestamp)

(3) write out the document

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); 

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?

like image 440
Wouter Lievens Avatar asked Jul 26 '10 13:07

Wouter Lievens


People also ask

How to add text in existing PDF using iText java?

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...


1 Answers

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(); 

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.

like image 143
gutch Avatar answered Sep 24 '22 18:09

gutch