Search code examples
javapdfitext

iText - add content to existing PDF file


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?


Solution

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