RadPdfViewer supports selection both through the UI and programmatically.
In order to be able to select text from the UI, RadPdfViewer must be in TextSelection mode. The mode of the viewer is specified by the Mode property, which could be set as follows:
this.pdfViewer.Mode = Telerik.Windows.Documents.Fixed.UI.FixedDocumentViewerMode.TextSelection;
More information on the different modes of the viewer can be found in this article.
When it comes to programmatic selection, it can occur even if the Mode of RadPdfViewer is not Selection.
All methods, properties and events relevant to the discussed functionality are contained in the TextSelection class.
- StartPosition: the TextPosition at which the selection starts. More information on TextPositions can be found here.
- EndPosition: The TextPosition denoting the end of the selection respectively.
- IsEmpty: A boolean property showing if there is selection in the current document.
The methods for manipulating the selection include:
public void SetSelectionStart(TextPosition startPosition) public void SetSelectionEnd(TextPosition endPosition) public void SetSelection(TextPosition startPosition, TextPosition endPosition) public void SelectAll() public void Clear() public string GetSelectedText() public void GetSelectedTextAsync(Action<string> callback)
Their names show clearly the action they execute.Here is an example showing how the functionality of TextPositions can be combined with that of TextSelection in order to select the word that the caret is currently positioned in:
TextPosition start = new TextPosition(this.pdfViewer.Document.CaretPosition); start.MoveToCurrentWordStart(); TextPosition end = new TextPosition(this.pdfViewer.Document.CaretPosition); end.MoveToCurrentWordEnd(); this.pdfViewer.Document.Selection.SetSelection(start, end); MessageBox.Show(this.pdfViewer.Document.Selection.GetSelectedText());
There are no genuine words in PDF, so the viewer uses a greedy text recognition method. That is why it is not guaranteed that it would find the exact start and end position of a word.
- SelectionChanging - occurs when you start to select part of the text.
- SelectionChanged - occurs when you have finished changing the current selection.