Modify existing PDF document using iText - Overlay images and Text

iText is very popular Java library for reading and manipulating PDF documents. In this tutorial we will take an existing document and overlay an image. The image can be put over the document or under it just like a watermark. Also we will add some text to the existing document. We can achieve all this with the help of the PdfStamper class.

PdfStamper applies extra content to the pages of a PDF document. This extra content can be all the objects allowed in PdfContentByte including pages from other Pdfs. The original PDF will keep all the interactive elements including bookmarks, links and form fields.

Before image of the PDF document

Modify existing PDF document using iText - add watermark and Text

After image of the PDF document

Modify existing PDF document using iText - add watermark and Text

As you can see one image is over the text and the other one is under it. Also there is text added for the page number as the bottom right corner. Here is the source code ...
package com.as400samplecode;

import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;

import java.io.FileOutputStream;
import java.io.IOException;

public class PdfStamperExample {

    public static void main(String[] args) {
        try {
            PdfReader pdfReader = new PdfReader("data/FormW4.pdf");

            PdfStamper pdfStamper = new PdfStamper(pdfReader,
                    new FileOutputStream("data/FormW4-Stamped.pdf"));

            Image image = Image.getInstance("data/Approved.png");

            for(int i=1; i<= pdfReader.getNumberOfPages(); i++){

                //put content under
                PdfContentByte content = pdfStamper.getUnderContent(i);
                image.setAbsolutePosition(100f, 150f);
                content.addImage(image);

                //put content over
                content = pdfStamper.getOverContent(i);
                image.setAbsolutePosition(300f, 150f);
                content.addImage(image);

                //Text over the existing page
                BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA,
                        BaseFont.WINANSI, BaseFont.EMBEDDED);
                content.beginText();
                content.setFontAndSize(bf, 18);
                content.showTextAligned(PdfContentByte.ALIGN_LEFT,"Page No: " + i,430,15,0);
                content.endText();

            }

            pdfStamper.close();

        } catch (IOException e) {
            e.printStackTrace();
        } catch (DocumentException e) {
            e.printStackTrace();
        }
    }
}

No comments:

Post a Comment

NO JUNK, Please try to keep this clean and related to the topic at hand.
Comments are for users to ask questions, collaborate or improve on existing.