以前写了一篇文章:读取PDF,这篇文章实现了同样的功能,在原来的基础上增加了上一页和下一页的功能。
pdfViewController.h
#import <UIKit/UIKit.h> #import "PDFView.h" @interface pdfViewController : UIViewController { IBOutlet PDFView *pdfview; } - (IBAction)goNextPage:(id)sender; - (IBAction)goPrePage:(id)sender; @end
pdfViewController.m
#import "pdfViewController.h" @implementation pdfViewController - (void)viewDidLoad { pdfview = [[PDFView alloc] initWithFrame:pdfview.frame andFileName:@"metro.pdf"]; [self.view addSubview:pdfview]; [pdfview release]; [super viewDidLoad]; } - (IBAction)goNextPage:(id)sender{ [pdfview goDownPage]; } - (IBAction)goPrePage:(id)sender{ [pdfview goUpPage]; } @end
PDFView.h
#import <UIKit/UIKit.h> @interface PDFView : UIView { //这个类封装了PDF画图的所有信息 CGPDFDocumentRef pdf; //PDFDocument中的一页 CGPDFPageRef page; //总共页数 int totalPages; //当前的页面 int currentPage; } //当前视图初始化类,在该方法中会创建一个CGPDFDocuemntRef对象,传递一个PDF文件的名字和所需要页面的大小 - (id)initWithFrame:(CGRect)frame andFileName:(NSString *)fileName; //创建一个PDF对象,此方法在初始化方法中被调用 - (CGPDFDocumentRef)createPDFFromExistFile:(NSString *)aFilePath; - (void)reloadView; //页面之间的跳转 - (void)goUpPage; - (void)goDownPage; @end
PDFView.m
#import "PDFView.h" @implementation PDFView - (id)initWithFrame:(CGRect)frame andFileName:(NSString *)fileName { if (self = [super initWithFrame:frame]) { NSString *dataPathFromApp = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:fileName]; pdf = [self createPDFFromExistFile:dataPathFromApp]; self.backgroundColor = [UIColor clearColor]; } return self; } - (CGPDFDocumentRef)createPDFFromExistFile:(NSString *)aFilePath { CFStringRef path; CFURLRef url; CGPDFDocumentRef document; path = CFStringCreateWithCString(NULL, [aFilePath UTF8String], kCFStringEncodingUTF8); url = CFURLCreateWithFileSystemPath(NULL, path, kCFURLPOSIXPathStyle, NO); CFRelease(path); document = CGPDFDocumentCreateWithURL(url); CFRelease(url); totalPages = CGPDFDocumentGetNumberOfPages(document); currentPage = 1; if (totalPages == 0) { return NULL; } return document; } - (void)drawRect:(CGRect)rect { //得到绘图上下文环境 CGContextRef context = UIGraphicsGetCurrentContext(); //得到一个PDF页面 page = CGPDFDocumentGetPage(pdf, currentPage); //进行坐标转换,这是因为Quartz的坐标系统是以左下角为起始点,但iPhone视图是以左上角为起始点 CGContextTranslateCTM(context, 0.0,self.bounds.size.height); //转变坐标系 CGContextScaleCTM(context, 1.0, -1); CGContextDrawPDFPage(context, page); } - (void)dealloc { [super dealloc]; } - (void)reloadView { [self setNeedsDisplay]; } - (void)goUpPage { if(currentPage < 2) return; --currentPage; [self reloadView]; } - (void)goDownPage { if(currentPage >= totalPages) return; ++currentPage; [self reloadView]; } @end