CodesJava

Easy learning with example program codes

How to modify an existing pdf file in java using iText jar?


To modify an existing pdf file using iText jar first download the iText jar files and include in the application classpath.

Steps:

1. Create PdfReader instance.
2. Create PdfStamper instance.
3. Create BaseFont instance.
4. Get the number of pages in pdf.
5. Iterate the pdf through pages.
6. Contain the pdf data using PdfContentByte.
7. Set text font and size.
8. Write text
9. Close the pdfStamper.

Example:

PDFModifyExample.java

import java.io.FileOutputStream;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
 
/**
 * This class is used to modify an existing pdf file using iText jar.
 * @author codesjava
 */
public class PDFModifyExample {
	public static void main(String args[]){
		try {
		    //Create PdfReader instance.
		    PdfReader pdfReader = 
				new PdfReader("D:\\TestFile.pdf");	
 
		    //Create PdfStamper instance.
		    PdfStamper pdfStamper = new PdfStamper(pdfReader,
			new FileOutputStream("D:\\ModifiedTestFile.pdf"));
 
		    //Create BaseFont instance.
		    BaseFont baseFont = BaseFont.createFont(
	                BaseFont.TIMES_ROMAN, 
	                BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
 
		    //Get the number of pages in pdf.
		    int pages = pdfReader.getNumberOfPages(); 
 
		    //Iterate the pdf through pages.
		    for(int i=1; i<=pages; i++) { 
			//Contain the pdf data.
			PdfContentByte pageContentByte = 
					pdfStamper.getOverContent(i);
 
			pageContentByte.beginText();
			//Set text font and size.
			pageContentByte.setFontAndSize(baseFont, 14);
 
			pageContentByte.setTextMatrix(50, 740);
 
			//Write text
			pageContentByte.showText("javawithease.com");
			pageContentByte.endText();
		    }
 
		    //Close the pdfStamper.
		    pdfStamper.close();	
 
		    System.out.println("PDF modified successfully.");
		} catch (Exception e) {
		    e.printStackTrace();
		}
	}
}

Output:

PDF modified successfully.

Download this example.
 

Sign Up/ Sign In
Ask a Question


Industrial Training

We offers Placement Oriented Training on Java, Spring, JSF, Hibernate, PHP, AngularJS, Angular 4, PLSQL, Oracle BI Publisher etc. We also provides Online training, please mail us at hr@codesjava.com.

Development

We also provides the Development services for Website Development , Java Development, PHP Development, Android App Development etc. You can contact us on hr@codesjava.com.

Copyright © 2018 CodesJava DMCA.com Protection Status SiteMap Reference: Java Wiki