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 javawithease
*/

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.

No comments: