Text Markup Annotations

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

Retrieve highlighted text

Highlighted text can be easily retrieved by TextMarkupAnnotation#getHighlightedText().

Copy
1
2
3
4
5
6
7
8
9
val pageIndex = 0
val annotations: List<Annotation> = document.annotationProvider.getAnnotations(pageIndex)
val highlightedTextMarkups: MutableList<String> = ArrayList()
for (annotation in annotations) {
    if (annotation is TextMarkupAnnotation) {
        val highlightedText = annotation.highlightedText
        highlightedText?.let { highlightedTextMarkups.add(it) }
    }
}
Copy
1
2
3
4
5
6
7
8
9
10
final int pageIndex = 0;
List<Annotation> annotations = document.getAnnotationProvider().getAnnotations(pageIndex);
List<String> highlightedTextMarkups = new ArrayList<>();
for (Annotation annotation : annotations) {
    if (annotation instanceof TextMarkupAnnotation) {
        TextMarkupAnnotation textMarkupAnnotation = (TextMarkupAnnotation) annotation;
        String highlightedText = textMarkupAnnotation.getHighlightedText();
        highlightedTextMarkups.add(highlightedText);
    }
}

Note: TextMarkupAnnotation#getHighlightedText() may return null if no text is highlighted.

Creating Markup Annotations From Page Text

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

For example, we'll highlight the first occurrence of a random string on the page:

Copy
1
2
3
4
5
6
7
8
9
// 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 annotation from text rectangles on the page.
    val annotation = HighlightAnnotation(pageIndex, document.getPageTextRects(pageIndex, textIndexOnPage, textToHighlight.length))
    // Add annotation to page.
    fragment.addAnnotationToPage(annotation, false)
}
Copy
1
2
3
4
5
6
7
8
9
// 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 annotation from text rectangles on the page.
    HighlightAnnotation annotation = new HighlightAnnotation(pageIndex, document.getPageTextRects(pageIndex, textIndexOnPage, textToHighlight.length()));
    // Add annotation to page.
    fragment.addAnnotationToPage(annotation, false);
}