iOS利用QLPreviewController显示PDF,word,execl,txt等格式的文件

翟浩穰
2023-12-01

以前预览PDF格式采用UIWebview,或者利用CGPDFDocumentGetPage显示。

今天发现QLPreviewController也可以实现预览PDF的功能,步骤如下:

1,在项目中导入QuickLook框架

2,引入QuickLook头文件,在项目中准备一下PDF的测试文件

3,

//
//  ViewController.m
//  QLPreviewControllerTest
//
//  Copyright © 2016年 digimagus. All rights reserved.
//

#import "ViewController.h"
#import <QuickLook/QuickLook.h>

@interface ViewController ()<QLPreviewControllerDelegate,QLPreviewControllerDataSource>

@end

@implementation ViewController
{
    NSArray *_PDFArray;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    UIButton * btn =[UIButton buttonWithType:UIButtonTypeSystem];
    
    btn.frame =CGRectMake(10, 100, 300, 40);
    
    [btn setTitle:@"打开" forState:UIControlStateNormal];
    
    [btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:btn];
    
    NSString *pdfPath = [[NSBundle mainBundle] pathForResource:@"test" ofType:@"pdf"];
    
    _PDFArray =@[pdfPath];
}


-(void)btnClick:(UIButton *)btn

{
    
    QLPreviewController* qlPreview = [[QLPreviewController alloc]init];
    
    qlPreview.dataSource= self; //需要打开的文件的信息要实现dataSource中的方法
    
    qlPreview.delegate= self;  //视图显示的控制
    
    [self presentViewController:qlPreview animated:YES completion:^{
        
        //需要用模态化的方式进行展示
        
    }];
    
}

#pragma mark - previewControllerDataSource

-(NSInteger)numberOfPreviewItemsInPreviewController:(QLPreviewController*)controller
{
    return _PDFArray.count; //需要显示的文件的个数
}

-(id<QLPreviewItem>)previewController:(QLPreviewController*)controller previewItemAtIndex:(NSInteger)index

{
    
    //返回要打开文件的地址,包括网络或者本地的地址
    
    NSURL * url =[NSURL fileURLWithPath:_PDFArray[index]];
    
    return url;
    
}

#pragma mark - previewControllerDelegate



-(CGRect)previewController:(QLPreviewController*)controller frameForPreviewItem:(id<QLPreviewItem>)iteminSourceView:(UIView *__autoreleasing *)view

{
    
    //提供变焦的开始rect,扩展到全屏
    
    return  CGRectMake(110, 190, 100, 100);
    
}


//
//-(UIImage *)previewController:(QLPreviewController*)controller transitionImageForPreviewItem:(id<QLPreviewItem>)itemcontentRect:(CGRect *)contentRect
//
//{
//    
//    //返回控制器在出现和消失时显示的图像
//    
//    return [UIImage imageNamed:@"gerenziliao_morentouxiang.png"];
//    
//}

-(void)previewControllerDidDismiss:(QLPreviewController*)controller

{
    
    //控制器消失后调用
    
}

-(void)previewControllerWillDismiss:(QLPreviewController*)controller

{
    
    //控制器在即将消失后调用
    
}
@end



 类似资料: