实现pdf文件的阅读。
使用自定义的UIView,继承自UIView,
1、项目中新建一个类,命名为PdfView。
#import <Foundation/Foundation.h>
@interface PdfView : UIView {
CGPDFDocumentRef pdf;
int pIndex;
}
@propertyint pIndex;
-(void)drawInContext:(CGContextRef)context;//进行绘制PDF
-(void)initPDF:(NSInteger)pageIndex;//初始化PDF
-(NSInteger) getNumberOfPages;//得到当前PDF的全部页数
@end
#import "PdfView.h"
@implementation PdfView
@synthesize pIndex;
- (id)initWithFrame:(CGRect)frame
{
self = [superinitWithFrame:frame];
if (self) {
}
return self;
}
//初始化,可以直接默认开始的页码。
- (void)initPDF:(NSInteger)pageIndex {
if(self != nil)
{
CFURLRef pdfURL = CFBundleCopyResourceURL(CFBundleGetMainBundle(), CFSTR("test1.pdf"), NULL, NULL);
pdf = CGPDFDocumentCreateWithURL((CFURLRef)pdfURL);
pIndex = pageIndex;
CFRelease(pdfURL);
}
}
-(NSInteger) getNumberOfPages {
returnCGPDFDocumentGetNumberOfPages(pdf);
}
-(void)drawInContext:(CGContextRef)context
{
// PDF page drawing expects a Lower-Left coordinate system, so we flip the coordinate system
// before we start drawing.
CGContextTranslateCTM(context, 0.0, self.bounds.size.height);
CGContextScaleCTM(context, 1.0, -1.0);
// Grab the first PDF page
CGPDFPageRef page = CGPDFDocumentGetPage(pdf, pIndex);
// We’re about to modify the context CTM to draw the PDF page where we want it, so save the graphics state in case we want to do more drawing
CGContextSaveGState(context);
// CGPDFPageGetDrawingTransform provides an easy way to get the transform for a PDF page. It will scale down to fit, including any
// base rotations necessary to display the PDF page correctly.
CGAffineTransform pdfTransform = CGPDFPageGetDrawingTransform(page, kCGPDFCropBox, self.bounds, 0, true);
// And apply the transform.
CGContextConcatCTM(context, pdfTransform);
// Finally, we draw the page and restore the graphics state for further manipulations!
CGContextDrawPDFPage(context, page);
CGContextRestoreGState(context);
}
- (void)drawRect:(CGRect)rect {
[selfdrawInContext:UIGraphicsGetCurrentContext()];
}
@end
2、在使用PDF的地方,导入这个类,然后
PdfView *pdfView = [[PdfViewalloc]initWithFrame:self.view.frame];
[pdfView initPDF:1];
[self.viewaddSubview:pdfView];
这样就可以看到第一页了,如果要实现翻页。就自己实现哈。