如何从iPhone的文档目录中读取pdf文件?

时间:2012-10-03 10:59:52

标签: iphone ios multithreading nsdocumentdirectory pdf-reader

目前我在iPhone应用程序中工作,我在资源文件夹(本地pdf文件)中有一个pdf文件,然后我成功阅读了pdf文件(paper.pdf),下面我提到了阅读本地pdf文件供您参考。< / p>

示例:

CFURLRef pdfURL = CFBundleCopyResourceURL(CFBundleGetMainBundle(), CFSTR("paper.pdf"), NULL, NULL);
pdf = CGPDFDocumentCreateWithURL((CFURLRef)pdfURL);
CFRelease(pdfURL);

然后我试图在NSDocument目录中存储pdf文件(来自URL),并成功存储。

NSData *pdfData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:@"http://www.msy.com.au/Parts/PARTS.pdf"]];

 NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
 NSString *documentsDirectory = [paths objectAtIndex:0]; 
 NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"myPDF11.pdf"];
 [pdfData writeToFile:filePath atomically:YES];

然后我尝试读取pdf文件(来自NSDocument目录),但我不知道,请帮帮我。

先谢谢

2 个答案:

答案 0 :(得分:9)

非常简单请使用下面的代码将文档目录中的pdf显示到Webview

从文档目录加载PDF

 - (void)viewDidLoad
 {
[super viewDidLoad];

UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 320, 367)];
webView.scalesPageToFit = YES;

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
 NSString *documentsDirectory = [paths objectAtIndex:0]; 
 NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"myPDF11.pdf"];

NSURL *targetURL = [NSURL fileURLWithPath:filePath];
NSURLRequest *request = [NSURLRequest requestWithURL:targetURL];
[webView loadRequest:request];

[self.view addSubview:webView];
[webView release];
 }

从应用包资源文件夹中加载PDF

 - (void)viewDidLoad
 {
[super viewDidLoad];

UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 320, 367)];
webView.scalesPageToFit = YES;

NSString *path = [[NSBundle mainBundle] pathForResource:@"myPDF11" ofType:@"pdf"];
NSURL *targetURL = [NSURL fileURLWithPath:path];
NSURLRequest *request = [NSURLRequest requestWithURL:targetURL];
[webView loadRequest:request];

[self.view addSubview:webView];
[webView release];
 }

答案 1 :(得分:8)

尝试使用它:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
NSString *documentsDirectory = [paths objectAtIndex:0]; 
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"myPDF11.pdf"];

NSURL *pdfUrl = [NSURL fileURLWithPath:filePath];
pdf = CGPDFDocumentCreateWithURL((CFURLRef)pdfURL);
CFRelease(pdfURL);

来自NSURL reference

  

NSURL课程与其核心基金会对应的CFURLRef免费桥接。有关免费桥接的更多信息,请参阅“免费桥接”。