Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Editing PDF text using Java

Tags:

java

pdf

Is there a way I can edit a PDF from Java?
I have a PDF document which contains placeholders for text that I need to be replaced using Java, but all the libraries that I saw created PDF from scratch and small editing functionality.
Is there anyway I can edit a PDF or is this impossible?

like image 287
Ammar Avatar asked Nov 09 '10 06:11

Ammar


People also ask

Can Apache open edit PDF?

From OpenOffice.org 3 you can install the PDF Import extension. It allows you to open a PDF file in Apache OpenOffice Drawing for an optimal layout accuracy. The text is shown in text boxes that can be edited.

Can we read PDF using Java?

Java For TestersThere are several libraries to read data from a pdf using Java. Let us see how to read data from a PDF document and display it on the console using a library named PDFBox. You can extract text using the getText() method of the PDFTextStripper class.


1 Answers

You can do it with iText. I tested it with following code. It adds a chunk of text and a red circle over each page of an existing PDF.

/* requires itextpdf-5.1.2.jar or similar */ import java.io.*; import com.itextpdf.text.DocumentException; import com.itextpdf.text.pdf.*;  public class AddContentToPDF {      public static void main(String[] args) throws IOException, DocumentException {          /* example inspired from "iText in action" (2006), chapter 2 */          PdfReader reader = new PdfReader("C:/temp/Bubi.pdf"); // input PDF         PdfStamper stamper = new PdfStamper(reader,           new FileOutputStream("C:/temp/Bubi_modified.pdf")); // output PDF         BaseFont bf = BaseFont.createFont(                 BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); // set font          //loop on pages (1-based)         for (int i=1; i<=reader.getNumberOfPages(); i++){              // get object for writing over the existing content;             // you can also use getUnderContent for writing in the bottom layer             PdfContentByte over = stamper.getOverContent(i);              // write text             over.beginText();             over.setFontAndSize(bf, 10);    // set font and size             over.setTextMatrix(107, 740);   // set x,y position (0,0 is at the bottom left)             over.showText("I can write at page " + i);  // set text             over.endText();              // draw a red circle             over.setRGBColorStroke(0xFF, 0x00, 0x00);             over.setLineWidth(5f);             over.ellipse(250, 450, 350, 550);             over.stroke();         }          stamper.close();      } } 
like image 188
bluish Avatar answered Oct 18 '22 20:10

bluish