Skip to content

Instantly share code, notes, and snippets.

Code to Find and Replace Text in PDF using Java. Here is linked article: https://kb.aspose.com/pdf/java/how-to-find-and-replace-text-in-pdf-using-java/
import com.aspose.pdf.Document;
import com.aspose.pdf.License;
public class FindAndReplaceTextInPdfUsingJava {
public static void main(String[] args) throws Exception {
// Instantiate license to create presentation in HTML
License pdfLicense = new License();
pdfLicense.setLicense("Aspose.Pdf.lic");
// Load the input PDF document
Document pdfDocument = new Document("Input.pdf");
// Create TextFragmentAbsorber object
com.aspose.pdf.TextFragmentAbsorber textFragmentAbsorber = new com.aspose.pdf.TextFragmentAbsorber("Rack");
// Set text replace options
com.aspose.pdf.TextReplaceOptions options = new com.aspose.pdf.TextReplaceOptions();
options.setReplaceScope(com.aspose.pdf.TextReplaceOptions.Scope.REPLACE_FIRST);
textFragmentAbsorber.setTextReplaceOptions(options);
// Accept the text absorber for the entire collection of pages
pdfDocument.getPages().accept(textFragmentAbsorber);
// Get the extracted fragments in a collection
com.aspose.pdf.TextFragmentCollection textFragmentCollection = textFragmentAbsorber.getTextFragments();
// Loop through all text fragments
for (com.aspose.pdf.TextFragment textFragment : textFragmentCollection) {
// Update the text
textFragment.setText("New Rack");
}
// Save the updated PDF file
pdfDocument.save("Output.pdf");
System.out.println("Done");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment