How to Add text to PDF file in Java

Hello Everyone! Here we will learn about how to add text to PDF document using Java.

How to write text to a PDF document in Java

In order to add text to an existing document, firstly we need to locate the required PDF document by importing the required packages mentioned below. Now create an instance to “PDDocument” and import the file name or file path to it as an argument. And then open the required page you want to add text to. Create an object to “PDPageContentStream” and add the document and page objects as an argument.

Now use the following methods to add text:

1.”beginText()”;

By using this method we can start adding text to the document.

2.”setFont()”;




By using this method we can add what kind of font style and size we want to.

3.Create a variable of type String and store the content which you wanted to add on the document

4.”showText()”;

By using this method, the stored content will be reflected in the PDF document.

import java.io.File; 
import java.io.IOException;  
import org.apache.pdfbox.pdmodel.PDDocument; 
import org.apache.pdfbox.pdmodel.PDPage; 
import org.apache.pdfbox.pdmodel.PDPageContentStream; 
import org.apache.pdfbox.pdmodel.font.PDType1Font;  

public class Main {  
   public static void main(String args[]) throws IOException {     
       
      PDDocument pdf = PDDocument.load(new File("pdf1.pdf")); 
      PDPage pg = pdf.getPage(0);       
      PDPageContentStream c= new PDPageContentStream(pdf,pg); 
      c.beginText();   
      c.setFont( PDType1Font.TIMES_ROMAN, 24 ); 
      String text="Text Added successfully"; 
      c.showText(text); 
      c.endText(); 
      c.close();      
      pdf.save(new File("pdf1.pdf"));  
      pdf.close();  
   }  
}

Finally, use method “endText();” to end adding text to the document. And then simply save the document passing the file name as an argument. Now close the PDF document.

This is how you can add text to an existing PDF document by java programming using the above methods. Hope the explanation is clear.

Also read:


Leave a Reply

Your email address will not be published. Required fields are marked *