Skip to content

构建一个功能基础的 PDF 阅读器(PDFViewCtrl)

本文介绍如何基于 FSPDFViewCtrl 构建一个功能基础的 PDF 阅读器(展示、缩放、翻页等基础交互),不包含 UI Extensions 的内置工具栏与功能模块。

前置条件

请先完成 集成福昕 PDF SDK(含工程创建、SDK 集成与授权初始化)。

步骤 1:使用 FSPDFViewCtrl 打开并显示 PDF

ViewController 中实例化 FSPDFViewCtrl,并调用 openDoc:password:completion: 打开文档。

Objective-C

objc
#import <FoxitRDK/FSPDFViewControl.h>
#import <FoxitRDK/FSPDFObjC.h>

@interface ViewController ()
@property (nonatomic, strong) FSPDFViewCtrl *pdfViewCtrl;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    // 初始化 FSPDFViewCtrl
    self.pdfViewCtrl = [[FSPDFViewCtrl alloc] initWithFrame:self.view.bounds];
    [self.view addSubview:self.pdfViewCtrl];

    // 打开 PDF 文档
    NSString *path = [[NSBundle mainBundle] pathForResource:@"Sample" ofType:@"pdf"];
    [self.pdfViewCtrl openDoc:path password:nil completion:^(FSErrorCode error) {
        if (error != FSErrSuccess) {
            NSLog(@"打开文档失败,错误码: %d", (int)error);
        }
    }];
}

@end

Swift

swift
import FoxitRDK

class ViewController: UIViewController {

    var pdfViewCtrl: FSPDFViewCtrl!

    override func viewDidLoad() {
        super.viewDidLoad()

        // 初始化 FSPDFViewCtrl
        pdfViewCtrl = FSPDFViewCtrl(frame: view.bounds)
        view.addSubview(pdfViewCtrl)

        // 打开 PDF 文档
        if let path = Bundle.main.path(forResource: "Sample", ofType: "pdf") {
            pdfViewCtrl.openDoc(path, password: nil) { error in
                if error != .errSuccess {
                    print("打开文档失败,错误码: \(error.rawValue)")
                }
            }
        }
    }
}

备注

上述示例从 App Bundle 加载文件。如需从 Documents 目录或网络加载,请参考 打开文档

步骤 2:监听文档事件(可选)

通过实现 IDocEventListener 协议,可以监听文档打开、关闭、保存等事件:

objc
// 注册文档事件监听
[self.pdfViewCtrl registerDocEventListener:self];

// 实现 IDocEventListener 协议
- (void)onDocOpened:(FSPDFDoc *)document error:(int)error {
    if (error == FSErrSuccess) {
        NSLog(@"文档已打开,共 %d 页", [self.pdfViewCtrl getPageCount]);
    }
}

- (void)onDocClosed:(FSPDFDoc *)document error:(int)error {
    NSLog(@"文档已关闭");
}