Text Extraction
Foxit PDF SDK for Android provides text extraction, selection, search, and retrieval APIs through the Core SDK. PDF text is organized in TextPage objects, one per page. With TextPage you can get characters, words, ranges, and text in rectangles.
TextPage is also used for:
- Text search: construct
TextSearchfromTextPage. - Hyperlinks: construct
PageTextLinksfromTextPage. - Selection highlight / region calculation: compute text regions from selection start and end points.
Get Page Text Rectangles from Selection Points
This example computes text rectangles from selection start and end points for highlight or range markup.
java
import com.foxit.sdk.PDFException;
import com.foxit.sdk.common.Constants;
import com.foxit.sdk.common.fxcrt.PointF;
import com.foxit.sdk.common.fxcrt.RectF;
import com.foxit.sdk.pdf.PDFPage;
import com.foxit.sdk.pdf.TextPage;
import java.util.ArrayList;
// Get the text area on page by selection.
// The starting selection position and ending selection position are specified by startPos and endPos.
public ArrayList<RectF> getTextRectsBySelection(PDFPage page, PointF startPos, PointF endPos) {
try {
// If the page hasn't been parsed yet, throw an exception.
if (!page.isParsed()) {
throw new PDFException(Constants.e_ErrNotParsed, "PDF Page should be parsed first");
}
// Create a text page from the parsed PDF page.
TextPage textPage = new TextPage(page, TextPage.e_ParseTextNormal);
if (textPage == null || textPage.isEmpty()) return null;
int startCharIndex = textPage.getIndexAtPos(startPos.getX(), startPos.getY(), 5);
int endCharIndex = textPage.getIndexAtPos(endPos.getX(), endPos.getY(), 5);
// API getTextRectCount requires that start character index must be lower than or equal to end character index.
startCharIndex = startCharIndex < endCharIndex ? startCharIndex : endCharIndex;
endCharIndex = endCharIndex > startCharIndex ? endCharIndex : startCharIndex;
int count = textPage.getTextRectCount(startCharIndex, endCharIndex - startCharIndex);
if (count > 0) {
ArrayList<RectF> array = new ArrayList<>();
for (int i = 0; i < count; i++) {
RectF rectF = textPage.getTextRect(i);
if (rectF == null || rectF.isEmpty()) continue;
array.add(rectF);
}
// The return rects are in PDF unit.
// If caller need to highlight the text rects on the screen, then these rects should be converted in device unit first.
return array;
}
} catch (PDFException e) {
e.printStackTrace();
}
return null;
}API Reference
See the API Reference for full TextPage documentation.