-->

如何读取文档目录PDF文件中的iPhone?(How to read pdf file from d

2019-08-01 02:50发布

目前我在iPhone应用程序中我的工作,我必须在资源文件夹(本地PDF文件)的PDF文件,然后我读PDF文件(paper.pdf)成功,下面我所提到的读取本地pdf文件,供大家参考。

例:

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目录),但我不知道,请帮助我。

提前致谢

Answer 1:

Try to use this:

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);

From NSURL reference:

The NSURL class is toll-free bridged with its Core Foundation counterpart, CFURLRef. For more information on toll-free bridging, see “Toll-Free Bridging”.



Answer 2:

它很简单,请使用以下代码从文件目录到网页视图显示您的PDF

从文档目录加载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];
 }


文章来源: How to read pdf file from document directory in iPhone?