Search code examples
javapdfitextpdfbox

How to edit the contents of an existing PDF programmatically in JAVA


Let's assume I have an existing pdf with a fixed header and footer and blank body like the below image

Empty PDF template

And I have to add content to the body(white part in the image)

How can I do that in java?


Solution

  •     PdfReader reader = new PdfReader("./the-pdf-where-you-want-to-insert-into.pdf");
        PdfStamper stamper = new PdfStamper(reader, new FileOutputStream("./destination.pdf"));
    
        PdfReader r = new PdfReader("./the-pdf-you-want-to-insert.pdf");
        PdfImportedPage page = stamper.getImportedPage(r, 1);
    
        Image instance = Image.getInstance(page);
    
        AffineTransform at = AffineTransform.getTranslateInstance(x, y); // x y positions where you want insert
        at.concatenate(AffineTransform.getScaleInstance(instance.getScaledWidth(), instance.getScaledHeight()));
    
        PdfContentByte canvas = stamper.getOverContent(1);
        canvas.addImage(instance, at);
    
        stamper.close();
        reader.close();