We're sorry Aspose doesn't work properply without JavaScript enabled.

Free Support Forum - aspose.com

PDF JAVA - Search Replace Strings

I need 2 things:

  1. search and replace strings.
  2. search and replace field values.

This is the code I’m using:

com.aspose.pdf.Document srcDoc = new com.aspose.pdf.Document(“example.pdf”);

String searchStr = “%%FIRSTNAME%%”;
String replaceStr = “JOHN”;
System.out.println("Searching: " + searchStr + " - " + replaceStr);

com.aspose.pdf.TextFragmentAbsorber textFragmentAbsorber = new com.aspose.pdf.TextFragmentAbsorber(searchStr);


com.aspose.pdf.TextFragmentCollection textFragmentCollection = textFragmentAbsorber.getTextFragments();

for(com.aspose.pdf.TextFragment textFragment : (Iterable<com.aspose.pdf.TextFragment>)textFragmentCollection)
System.out.println("Replacing: " + searchStr + " - " + replaceStr);

The above code doesn’t replace field values. How can I replace pdf field values?

Kind regards,

Hi Renato,

Thanks for contacting support.

The above code snippet provides the capabilities to replace text inside PDF file. However in order to replace/update values inside form fields, please try using instructions specified over Get and Set value of Form Field in a PDF Document.

In case you encounter any issue, please share the input PDF file, so that we can test the scenario in our environment.

Thank you for your reply.

The main question I have is: how do I find and replace the %%FIRSTNAME%% .OoPdfFormExample.pdf (214.4 KB)

I’ve attached an example.

Kind regards,

Hi Renato,

Thanks for sharing the sample file.

In order to update the value in form field, please try using following code snippet. For your reference, I have also attached the resultant document with updated value Form_Filled.pdf (215.1 KB)


// load input PDF form
com.aspose.pdf.Document srcDoc = new com.aspose.pdf.Document("c:/pdftest/OoPdfFormExample.pdf");
// get names of form fields
Field[] fields = srcDoc.getForm().getFields();
for (int i = 0; i < fields.length; i++) {
    // print form field names and values
    System.out.println("Form field name " + fields[i].getFullName());
    System.out.println("Form field value: " + fields[i].getValue());
// Get reference of specific form field
TextBoxField textBoxField = (TextBoxField) srcDoc.getForm().get("Given Name Text Box");
// Set the field value
// save PDF document