读取PDF

PDFAppDelegate.h

 

#import <UIKit/UIKit.h>

@interface PDFAppDelegate : NSObject <UIApplicationDelegate> {
    UIWindow *window;
	IBOutlet UIScrollView *scrollView;
}

@property (nonatomic, retain) IBOutlet UIWindow *window;

@end

 

PDFAppDelegate.m 

 

#import "PDFAppDelegate.h"
#import "PDFView.h"

@implementation PDFAppDelegate

@synthesize window;

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
	NSString *filePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"metro_geo.pdf"];	
	PDFView *pdfView = [[PDFView alloc] initWithFilePath:filePath];
	scrollView.contentSize = pdfView.frame.size;
	[scrollView addSubview:pdfView];
	[pdfView release];	
    [window makeKeyAndVisible];	
	return YES;
}

- (void)dealloc {
    [window release];
    [super dealloc];
}

@end

 

PDFView.h

 

#import <UIKit/UIKit.h>

@interface PDFView : UIView {
	CGPDFDocumentRef pdfRef;
	CGPDFPageRef page;
}

- (id)initWithFilePath:(NSString *)filePath;
- (void)reloadView;
- (CGPDFDocumentRef)createPDFFromExistFile:(NSString *)aFilePath;

@end

 

PDFView.m

 

#import "PDFView.h"

@implementation PDFView

- (id)initWithFilePath:(NSString *)filePath {
	pdfRef = [self createPDFFromExistFile:filePath];
	CGPDFPageRef pdfPage = CGPDFDocumentGetPage(pdfRef, 1);
	CGRect mediaRect = CGPDFPageGetBoxRect(pdfPage, kCGPDFMediaBox);
	self = [super initWithFrame:mediaRect];
	return self;
}

- (void)drawRect:(CGRect)rect {
	CGContextRef context = UIGraphicsGetCurrentContext();	
	[[UIColor whiteColor] set];
	CGContextFillRect(context, rect);	
	CGContextGetCTM(context);
	CGContextScaleCTM(context, 1, -1);
	CGContextTranslateCTM(context, 0, -rect.size.height);	
	page = CGPDFDocumentGetPage(pdfRef, 1);	
	CGRect mediaRect = CGPDFPageGetBoxRect(page, kCGPDFCropBox);
	CGContextScaleCTM(context, rect.size.width / mediaRect.size.width, rect.size.height / mediaRect.size.height);
	CGContextTranslateCTM(context, -mediaRect.origin.x, -mediaRect.origin.y);	
	CGContextDrawPDFPage(context, page);
}

- (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);
	int count = CGPDFDocumentGetNumberOfPages(document);
    if (count == 0) {
		return NULL;
    }
	return document;
}

- (void)dealloc {
    [super dealloc];
}

- (void)reloadView{
	[self setNeedsDisplay];
}

@end

 

你可能感兴趣的:(ios,iPhone,pdf)