Text Search

Extracting and searching text in PDF can be quite complex, and we offer several abstractions to make this simpler.

Extracting Text

PSPDFTextParser offers a simple API to get the text, glyphs (PSPDFGlyph), words (PSPDFWord), textBlocks (PSPDFTextBlock) and even images (PSPDFImageInfo). In a PDF text is usually just absolutely positioned glyphs. PSPDFKit uses approximation to group words and text blocks. You can fetch the text parser via textParserForPageAtIndex: method on PSPDFDocument.

Searching

Searching via PSPDFViewController

In most cases, you just want to trigger a search inside the PSPDFViewController. This can be done by calling searchForString:options:sender:animated:. We'll automatically anchor the popover to the search button or show a modal dialog for compact size classes like the iPhone. Options can take one parameter: PSPDFViewControllerSearchHeadlessKey which invokes a search but does not trigger any UI. This is great for unobtrusive highlighting.

Copy
1
2
let searchString = "Example Search Text"
pdfController.search(for: searchString, options: [PSPDFViewControllerSearchHeadlessKey: true], sender: nil, animated: true)
Copy
1
2
NSString *searchString = @"Example Search Text";
[pdfController searchForString:searchString options:@{PSPDFViewControllerSearchHeadlessKey: @YES} sender:nil animated:YES];

Searching Manually

To search text inside a document, create an instance of PSPDFTextSearch, passing in the loaded PSPDFDocument via its initializer. Searching can be triggered via calling searchForString:, which will start a search in a background queue. Implement PSPDFTextSearchDelegate on the receiving object and set the text search object's delegate to your object to be notified of search result updates.

Important: You need to retain the text search object while search is running, else any running search is automatically cancelled and your delegate will not get called.

Specify search options

Before triggering a search, you can configure various search options:

Changing these properties one a search operation is running is not supported and might result in unexpected behavior.

Highlighting Search Results

Search results are represented by PSPDFSearchResult and offer both the content (selection) as PSPDFTextBlock and a previewText. You can use these objects to represent your own search result list, or manually highlight parts of a page.

The PSPDFSearchHighlightViewManager manages the task of showing and hiding search results. It can be accessed via the searchHighlightViewManager property on PSPDFViewController and offers a way to both add (addHighlightSearchResults:animated:) and clear (clearHighlightedSearchResultsAnimated:) search results.

The PSPDFSearchHighlightView will be added on top of a visible PSPDFPageView for each search result. It can be customized via UIAppearance - see selectionBackgroundColor and cornerRadiusProportion.