天堂向右,我依然向左

天下之大,虽离家千里,何处不可往!何事不可为!
生活之路,纵坎坷曲折,当奋斗不息,则精彩纷呈!

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::
怎么在iPhone程序中读取PDF的内 容呢?答案是,苹果为我们准备了一个很神奇的framework Q2D(Quartz 2D)。Q2D提供了全套的PDF读取API,接下来我们来看看如果简单的使用Q2D来读取PDF文件:

 我建立了一个工程叫iPhonePDF, 添加了一个UIScrollView(不知道怎么添加UIScrollView? 添加一个UIView然后把interface上的UIView改成UIScrollView就可以啦…)名为PDFView

看看 PDFView里面有什么吧

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@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文件里面有用的方 法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
@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

 

posted on 2010-09-12 10:39  老舟  阅读(983)  评论(0编辑  收藏  举报