In order to search PDF, we’ll use Aspose.PDF for Java API which is a feature-rich, powerful and easy to use conversion API for Java platform. You can download its latest version directly from Maven and install it within your Maven-based project by adding the following configurations to the pom.xml.
<repository>
<id>AsposeJavaAPI</id>
<name>Aspose Java AP</name>
<url>https://releases.aspose.com/java/repo/</url>
</repository>
<dependency>
<groupId>com.aspose</groupId>
<artifactId>aspose-pdf</artifactId>
<version>version of aspose-pdf API</version>
</dependency>
Search PDF File via Java
You need Aspose.PDF for Java to try the code in your environment.
- Load the PDF with an instance of Document.
- Create TextFragmentAbsorber Object with text to find as parameter.
- Get all extracted text fragments collection.
- Loop through each fragment to get all of its information.
Search PDF Files - Java
// Load PDF document
Document pdfDocument = new Document("source.pdf");
// Create TextAbsorber object to find all instances of the input search phrase
TextFragmentAbsorber textFragmentAbsorber = new TextFragmentAbsorber("\d{4}-\d{4}"); // like 1999-2000
// Set text search option to specify regular expression usage
TextSearchOptions textSearchOptions = new TextSearchOptions(true);
textFragmentAbsorber.setTextSearchOptions(textSearchOptions);
// Accept the absorber for first page of document
pdfDocument.getPages().accept(textFragmentAbsorber);
// Get the extracted text fragments into collection
TextFragmentCollection textFragmentCollection = textFragmentAbsorber.getTextFragments();
// Loop through the fragments
for (TextFragment textFragment : (Iterable<TextFragment>) textFragmentCollection) {
System.out.println("Text :- " + textFragment.getText());
System.out.println("Position :- " + textFragment.getPosition());
System.out.println("XIndent :- " + textFragment.getPosition().getXIndent());
System.out.println("YIndent :- " + textFragment.getPosition().getYIndent());
System.out.println("Font - Name :- " + textFragment.getTextState().getFont().getFontName());
System.out.println("Font - IsAccessible :- " + textFragment.getTextState().getFont().isAccessible());
System.out.println("Font - IsEmbedded - " + textFragment.getTextState().getFont().isEmbedded());
System.out.println("Font - IsSubset :- " + textFragment.getTextState().getFont().isSubset());
System.out.println("Font Size :- " + textFragment.getTextState().getFontSize());
System.out.println("Foreground Color :- " + textFragment.getTextState().getForegroundColor());
}