Creating Markup Annotations from Page Text

PSPDFKit provides an abstract class, TextMarkupAnnotation, for all text markup annotations: HighlightAnnotation, SquigglyAnnotation, UnderlineAnnotation, and StrikeOutAnnotation.

Creating Markup Annotations from Page Text

You can retrieve text rectangles required to create markup annotations by calling PdfDocument#getPageTextRects.

For example, you’ll highlight the first occurrence of a random string on the page:

// Search for the position of text that should be highlighted on the page.
val textToHighlight = "text to highlight"
val textIndexOnPage = document.getPageText(pageIndex).indexOf(textToHighlight)
if (textIndexOnPage >= 0) {
    // Create an annotation from the text rectangles on the page.
    val annotation = HighlightAnnotation(pageIndex, document.getPageTextRects(pageIndex, textIndexOnPage, textToHighlight.length))
    // Add the annotation to the page.
    fragment.addAnnotationToPage(annotation, false)
}
// Search for the position of text that should be highlighted on the page.
String textToHighlight = "text to highlight";
int textIndexOnPage = document.getPageText(pageIndex).indexOf(textToHighlight);
if (textIndexOnPage >= 0) {
    // Create an annotation from the text rectangles on the page.
    HighlightAnnotation annotation = new HighlightAnnotation(pageIndex, document.getPageTextRects(pageIndex, textIndexOnPage, textToHighlight.length()));
    // Add the annotation to the page.
    fragment.addAnnotationToPage(annotation, false);
}