Extract Selected Text from PDFs on iOS

PSPDFKit’s document viewing UI has built-in support for text selection, which was designed to exactly match the text selection behavior in stock iOS components. The text selection UI includes full support standard touch and cursor-based text selection gestures, a built-in contextual menu, and support for multi-finger system gestures for text operations such as copying.

In addition to the bundled UI behaviors, it’s also possible to build additional operations on the selected text by leveraging the provided API hooks. This guide covers two convenient options.

Selection Callback

PDFViewController can inform your code of text selection changes via a dedicated delegate callback. To use it, assign PDFViewController.delegate to your object and implement the pdfViewController(_,didSelectText:,with:,at:,on:) callback:

pdfController.delegate = self

// MARK: `PDFViewControllerDelegate`

func pdfViewController(_ pdfController: PDFViewController, didSelectText text: String, with glyphs: [Glyph], at rect: CGRect, on pageView: PDFPageView) {
    // Do something with the selected text.
    print(text)
}

Text Selection View

Each visible PDF page of a document in a PDFViewController will be represented by a PageView instance in the view hierarchy. Those objects in turn reference a TextSelectionView instance, which exposes various operations related to text selection.

To get an array of all the selected text blocks on the visible pages, you can use the following code snippet:

let selectedText = pdfController.visiblePageViews.compactMap { pageView in
    return pageView.selectionView.selectedText
}