怎么在iPhone程序中读取PDF的内 容呢?答案是,苹果为我们准备了一个很神奇的framework Q2D(Quartz 2D)。Q2D提供了全套的PDF读取API,接下来我们来看看如果简单的使用Q2D来读取PDF文件:
我建立了一个工程叫iPhonePDF, 添加了一个UIScrollView(不知道怎么添加UIScrollView? 添加一个UIView然后把interface上的UIView改成UIScrollView就可以啦…)名为PDFView
看看 PDFView里面有什么吧
@interface PDFView : UIScrollView {
NSString *filePath;
CGPDFDocumentRef pdfDocument;
CGPDFPageRef page;
int pageNumber;
}
@property (copy, nonatomic) NSString *filePath;
@property int pageNumber;
-(CGPDFDocumentRef)MyGetPDFDocumentRef;
-(void)reloadView;
-(IBAction)goUpPage:(id)sender;
-(IBAction)goDownPage:(id)sender;
@end
filePath 是储存pdf文件的位置的,得到文件位置就是老话题了:[NSBundle mainBundle]… 后面的会写吧… 不记得了在我博客里面搜索吧
CGPDFDocumentRef 是PDF文档索引文件,Q2D是Core Foundation的API,所以没看到那个星星~
CGPDFPageRef 是PDF页面索引文件
pageNumber 是页码
下面的几 个函数其实一看就明了了,翻页的,和刷新页面的。第一个是自定义的getter
然后我们看看m文件里面有用的方 法:
@implementation PDFView
@synthesize filePath,pageNumber;
- (void)drawRect:(CGRect)rect //只要是UIView都有的绘图函数,基础哟~
{
if(filePath == nil) //如果没被初始化的话,就初始化
{
pageNumber = 10; //这个其实应该由外部函数控制,不过谁让这个程序特别简单呢
filePath = [[NSBundle mainBundle] pathForResource:@"zhaomu" ofType:@"pdf"];
//这里,文件在这里!
pdfDocument = [self MyGetPDFDocumentRef]; //从自定义getter得到文件索引
}
CGContextRef myContext = UIGraphicsGetCurrentContext();
//这个我研究了一段时间呢,不过就照打就可以了
page = CGPDFDocumentGetPage(pdfDocument, pageNumber);
//便捷函数,告诉 人家文档,告诉人家页码,就给你页面索引
CGContextDrawPDFPage(myContext, page);
//画!
}
//此 getter可以考虑照打... 都是CF函数,我看到就恶心。
//其实不是很难了,得到文件,转换成URL,然后通过
//CGPDFDocumentCreateWithURL(url) 得到文件内容索引
//Ta Daaa~~
- (CGPDFDocumentRef)MyGetPDFDocumentRef
{
CFStringRef path;
CFURLRef url;
CGPDFDocumentRef document;
path = CFStringCreateWithCString(NULL, [filePath UTF8String], kCFStringEncodingUTF8);
url = CFURLCreateWithFileSystemPath(NULL, path, kCFURLPOSIXPathStyle, 0);
CFRelease(path);
document = CGPDFDocumentCreateWithURL(url);
CFRelease(url);
return document;
}
-(void)reloadView
{
[self setNeedsDisplay]; //每次需要重画视图了,就call这个
}
-(IBAction)goUpPage:(id)sender
{
pageNumber++;
[self reloadView];
}
-(IBAction)goDownPage:(id)sender
{
pageNumber--;
[self reloadView];
}
@end