IOS--PDF顯示(CGPDFDocumentRef)


摘要: 學習使用自定義view加載顯示pdf;

前言

在IOS中預覽pdf文件,顯示pdf文件一般使用兩種方式,一種是UIWebView,這種方式怎么說呢優點就是除了簡單還是簡單,直接顯示pdf文件;另外的一種是自定義UIView,配合CGPDFDocumentRef讀取pdf文件里面的內容,在自定義的drawRect方法中描繪獲取的pdf內容;其實還有一種的方式,就是蘋果在IOS4.0后,apple推出新的文件預覽控件:QLPreveiewController,支持pdf文件閱讀。今天我主要寫的是自定義View+CGPDFDocumentRef顯示pdf文件;

 

(一)先運用CGPDFDocumentRef獲取指定的pdf內容;下面是我寫出的獲取內容的方法;

 1 //用於本地pdf文件
 2 - (CGPDFDocumentRef)pdfRefByFilePath:(NSString *)aFilePath {
 3     CFStringRef path;
 4     CFURLRef url;
 5     CGPDFDocumentRef document;
 6     
 7     path = CFStringCreateWithCString(NULL, [aFilePath UTF8String], kCFStringEncodingUTF8);
 8     url = CFURLCreateWithFileSystemPath(NULL, path, kCFURLPOSIXPathStyle, NO);
 9     document = CGPDFDocumentCreateWithURL(url);
10     
11     CFRelease(path);
12     CFRelease(url);
13     
14     return document;
15 }
16 
17 - (NSString *)getPdfPathByFile:(NSString *)fileName {
18     return [[NSBundle mainBundle] pathForResource:fileName ofType:@".pdf"];
19 }
20 
21 //用於網絡pdf文件
22 - (CGPDFDocumentRef)pdfRefByDataByUrl:(NSString *)aFileUrl {
23     NSData *pdfData = [NSData dataWithContentsOfFile:aFileUrl];
24     CFDataRef dataRef = (__bridge_retained CFDataRef)(pdfData);
25     
26     CGDataProviderRef proRef = CGDataProviderCreateWithCFData(dataRef);
27     CGPDFDocumentRef pdfRef = CGPDFDocumentCreateWithProvider(proRef);
28     
29     CGDataProviderRelease(proRef);
30     CFRelease(dataRef);
31     
32     return pdfRef;
33 }

 

通過文件路徑解析pdf文件,返回文件內容。

 

(二)第二步就是在自定義的View中繪制pdf內容;

- (void)drawRect:(CGRect)rect {
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGPDFPageRef pageRef = CGPDFDocumentGetPage([self createPDFFromExistFile], _pageNumber);//獲取指定頁的內容如_pageNumber=1,獲取的是pdf第一頁的內容
    CGRect mediaRect = CGPDFPageGetBoxRect(pageRef, kCGPDFCropBox);//pdf內容的rect
    
    CGContextRetain(context);
    CGContextSaveGState(context);
    
    [[UIColor whiteColor] set];
    CGContextFillRect(context, rect);//填充背景色,否則為全黑色;
    
    CGContextTranslateCTM(context, 0, rect.size.height);//設置位移,x,y;
    
    CGFloat under_bar_height = 64.0f;
    CGContextScaleCTM(context, rect.size.width / mediaRect.size.width, -(rect.size.height + under_bar_height) / mediaRect.size.height);
    
    CGContextSetInterpolationQuality(context, kCGInterpolationHigh);
    CGContextSetRenderingIntent(context, kCGRenderingIntentDefault);
    CGContextDrawPDFPage(context, pageRef);//繪制pdf
    
    CGContextRestoreGState(context);
    CGContextRelease(context);
}

 

以上就是繪制pdf的內容的代碼,代碼每行我都寫了注釋,其實都是很好了解的。

當然上面的只是顯示pdf指定頁的邏輯,要想顯示整個pdf文件的內容,需要配合UIScrollView或者是UIPageViewController去實現,原理也很簡單,結合上述的邏輯只要傳入一個pageIndex的值,刷新頁面內容就可以實現。下面是我寫的一個列子,pageviewcontroller實現;

- (void)viewDidLoad {
    [super viewDidLoad];
    self.pdfArr = [NSMutableArray array];
    NSDictionary *options = [NSDictionary  dictionaryWithObject:[NSNumber numberWithInteger:UIPageViewControllerSpineLocationMin] forKey:UIPageViewControllerOptionSpineLocationKey];
    self.pageVC = [[UIPageViewController alloc]initWithTransitionStyle:UIPageViewControllerTransitionStylePageCurl navigationOrientation:UIPageViewControllerNavigationOrientationHorizontal options:options];
    _pageVC.view.frame = self.view.bounds;
    _pageVC.delegate = self;
    _pageVC.dataSource = self;
    [self addChildViewController:_pageVC];
    
    PDFView *testPdf = [[PDFView alloc]initWithFrame:self.view.frame atPage:1 andFileName:@"Reader"];
    CGPDFDocumentRef pdfRef = [testPdf createPDFFromExistFile];
    size_t count = CGPDFDocumentGetNumberOfPages(pdfRef);//這個位置主要是獲取pdf頁碼數;
    
    for (int i = 0; i < count; i++) {
        UIViewController *pdfVC = [[UIViewController alloc] init];
        PDFView *pdfView = [[PDFView alloc] initWithFrame:self.view.frame atPage:(i+1) andFileName:@"Reader"];
        [pdfVC.view addSubview:pdfView];
        
        [_pdfArr addObject:pdfVC];
    }
    
    
    [_pageVC setViewControllers:[NSArray arrayWithObject:_pdfArr[0]] direction:UIPageViewControllerNavigationDirectionForward animated:YES completion:nil];
    [self.view addSubview:_pageVC.view];
    
}
//委托方法;
- (UIViewController *)viewControllerAtIndex:(NSInteger)index
{
    //Create a new view controller and pass suitable data.
    
    if (([_pdfArr count] == 0 )|| (index > [_pdfArr count]) ) {
        return nil;
    }
    
    
    NSLog(@"index = %ld",(long)index);
    
    return (UIViewController *)_pdfArr[index];
}


- (NSUInteger) indexOfViewController:(UIViewController *)viewController
{
    return [self.pdfArr indexOfObject:viewController];
}


- (UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerAfterViewController:(UIViewController *)viewController
{
    NSUInteger index = [self indexOfViewController:(UIViewController *)viewController];
    if (index == NSNotFound) {
        return nil;
    }
    
    index++;
    
    if (index == [_pdfArr count]){
        return  nil;
    }
    
    return [self viewControllerAtIndex:index];
}

- (UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerBeforeViewController:(UIViewController *)viewController
{
    NSUInteger index = [self indexOfViewController:(UIViewController *)viewController];
    if ((index == 0 ) || (index == NSNotFound)){
        return nil;
    }
    
    index--;
    
    return [self viewControllerAtIndex:index];
}

 

以上就是簡單的實現;

 

(三)對於第三種方法,使用QLPreveiewController去預覽pdf,我就沒有具體的通過代碼去實現pdf的預覽,在網絡上應該有資源可查;

QLPreveiewController的用法;已經簡單的說了一下怎么去預覽pdf內容,也是很簡單的,如果想要自定義顯示的話,需要自己花時間去研究了。

 

總結

不管是選用哪一種方式,都可以實現加載pdf文件;webview除了簡單粗暴但是只能作為簡單的瀏覽,CGPDFDocumentRef需要開發者自己去實現顯示的邏輯,但這樣可控性會比較好,顯示的效果也是可以自定義,QLPreveiewController的話,我沒有自己去實現過,所以大家可以去試試。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM