iOS 加载PDF(docx文件加载失败可以转为PDF再加载)

加载pdf方法有多种;根据来吧。下面介绍WKWebVIew 和QLPreviewController

1 WKWebVIew 这个就简单直接上代码:

#import 


@interface PrivacyViewController ()
@property(nonatomic,strong)WKWebView *webView;
@property(nonatomic,strong)UIButton *backBtn;
@end

@implementation PrivacyViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
   self.view.backgroundColor =  [UIColor colorWithRed:0 green:0 blue:0 alpha:0.5];
    
    _webView =[[WKWebView alloc]initWithFrame:CGRectMake(0, 0, KWidth, KHeight)];
    [self.view addSubview:_webView];
    _webView.backgroundColor = Common_fg_f1_color;
    NSString *documentLocation=[[NSBundle mainBundle]pathForResource:@"privacy" ofType:@"pdf"];
    NSURL *myDocument=[NSURL fileURLWithPath:documentLocation];
    NSURLRequest *request=[NSURLRequest requestWithURL:myDocument];
    [_webView loadRequest:request];
   
    _webView.navigationDelegate = self;
    
    [self showLoadView];
    
    self.backBtn = [[UIButton alloc]init];
    self.backBtn.frame = CGRectMake(kMargin_16, 40, 40, 40);
    self.backBtn.layer.cornerRadius  = self.backBtn.height/2;
    self.backBtn.layer.masksToBounds = YES;
    [self.view addSubview:self.backBtn];
    self.backBtn.backgroundColor = Common_line_shadow_color;
    [self.backBtn setImage:[UIImage imageNamed:@"back"] forState:(UIControlStateNormal)];
    [self.backBtn addTarget:self action:@selector(backAction) forControlEvents:(UIControlEventTouchUpInside)];
}

-(void)backAction{
    [self dismissViewControllerAnimated:YES completion:nil];
}


// 页面加载完成之后调用
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
 [self closeLoadView];
}


@end

2 QLPreviewController 这个就复杂点;

 a 添加库 (Bulid Phases  添加 QuickLook库);  b 引入头文件 (#import );c  各种代理;

#import 

//打开PDF文档需要引入的视图控制器
@property (nonatomic, strong)QLPreviewController *previewController;
//文件路径
@property (nonatomic, copy)NSString *path;

//使用的是本地路径 
  self.path = [[NSBundle mainBundle]pathForResource:@"aa" ofType:@"pdf"];


#pragma mark -隐私声明

/**

查看文件按钮点击方法

*/

/**

文档数量

*/

- (NSInteger)numberOfPreviewItemsInPreviewController: (QLPreviewController *) controller{

return 1;

}

/**

//打开文件的地址

*/

- (id)previewController: (QLPreviewController *)controller previewItemAtIndex:(NSInteger)index {

//打开文件的地址,包括网络或者本地的地址

return [NSURL fileURLWithPath:self.path];

}

/**

点击Done方法(阅读器已经消失的时候调用)

*/

- (void)previewControllerDidDismiss:(QLPreviewController *)controller {

}


使用点击时调用:

    QLPreviewController *previewController = [[QLPreviewController alloc]init];
    previewController.delegate = self;
    previewController.dataSource = self;
    [self presentViewController:previewController animated:YES completion:nil];


tip: 加载大量PDF时 ,模拟器会有很长时间延时,真机秒开。最好的办法就是直接给url 然后 we b加载。很多文件也可以下载压缩包解包后存在本地然后加载。如需加载本地docx文件可转为pdf在加载。

 

 

 

你可能感兴趣的:(iOS开发)