Skip to content

文本提取

福昕 PDF SDK iOS 版通过 Core SDK 提供用于文本提取、选择、搜索与检索的 API。PDF 的文本内容由 FSTextPage 对象进行组织,并与具体页面一一对应。通过 FSTextPage,可获取页面中的字符、单词、指定范围文本,以及指定矩形区域内的文本等信息。

FSTextPage 也常用于构建其它文本相关能力:

  • 文本搜索:用 FSTextPage 构造 FSTextSearch
  • 超链接访问:用 FSTextPage 构造 FSPageTextLinks
  • 选中文本高亮/区域计算:用 FSTextPage 根据选择起止点计算文字区域。

示例:提取页面全部文本

objc
#import <FoxitRDK/FSPDFObjC.h>

FSPDFDoc *doc = [[FSPDFDoc alloc] initWithPath:@"path/to/Sample.pdf"];
[doc load:nil];

FSPDFPage *page = [doc getPage:0];
[page startParse:FSPDFPageParsePageNormal pause:nil is_reparse:YES];

FSTextPage *textPage = [[FSTextPage alloc] initWithPage:page flags:FSTextPageParseTextNormal];
NSString *fullText = [textPage getChars:0 count:-1];
NSLog(@"页面文本: %@", fullText);

示例:根据选择起止点获取文本区域

本示例演示如何根据选择起止点计算文字区域,用于选中高亮或范围标注等场景。

objc
- (NSArray<NSValue *> *)getTextRectsBySelectionOnPage:(FSPDFPage *)page
                                             startPos:(FSPointF *)startPos
                                               endPos:(FSPointF *)endPos {
    FSTextPage *textPage = [[FSTextPage alloc] initWithPage:page
                                                      flags:FSTextPageParseTextNormal];
    if (!textPage) return nil;

    int startIndex = [textPage getIndexAtPos:[startPos getX] y:[startPos getY] tolerance:5];
    int endIndex = [textPage getIndexAtPos:[endPos getX] y:[endPos getY] tolerance:5];

    if (startIndex > endIndex) {
        int temp = startIndex;
        startIndex = endIndex;
        endIndex = temp;
    }

    int count = [textPage getTextRectCount:startIndex count:endIndex - startIndex];
    if (count <= 0) return nil;

    NSMutableArray *rects = [NSMutableArray array];
    for (int i = 0; i < count; i++) {
        FSRectF *rect = [textPage getTextRect:i];
        if (rect) {
            // 返回的矩形为 PDF 坐标系,在屏幕显示前需转换为设备坐标
            [rects addObject:[NSValue valueWithCGRect:CGRectMake(
                [rect getLeft], [rect getTop],
                [rect getRight] - [rect getLeft],
                [rect getTop] - [rect getBottom])]];
        }
    }
    return rects;
}

API 参考

FSTextPage 的完整接口说明请参阅 API 手册