在iphone的UIWebView中显示本地pdf文件

时间:2013-04-16 05:27:35

标签: iphone uiwebview

我在UIWebView中显示本地pdf文件但它在路径中显示异常是我的代码

     NSString*fileName=content_Source;
     NSString *path = [[NSBundle mainBundle] pathForResource:fileName ofType:@"pdf"];
     NSURL *url = [NSURL fileURLWithPath:path];
     NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [webView setScalesPageToFit:YES];
    [webView loadRequest:request]

4 个答案:

答案 0 :(得分:6)

设置文件名时必须使用文件扩展名。因此,如果其设置与Type(如ofType:@“pdf”)一样,请确保该扩展名不会在文件名中使用。

这是我的代码:

UIWebView *webView = [[UIWebView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
webView.backgroundColor = [UIColor redColor];
NSString*fileName= @"About_Downloads";
NSString *path = [[NSBundle mainBundle] pathForResource:fileName ofType:@"pdf"];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL fileURLWithPath:path isDirectory:NO]];
[webView setScalesPageToFit:YES];
[webView loadRequest:request];
[self.view addSubview:webView];

有一种更好的方式来展示pdf:

UIDocumentInteractionController *dc = [UIDocumentInteractionController interactionControllerWithURL:[NSURL fileURLWithPath:path isDirectory:NO]];
dc.delegate = self; 
[dc presentPreviewAnimated:YES];

确保将代理与该代码一起使用才能正常使用。

(UIViewController *)documentInteractionControllerViewControllerForPreview:(UIDocumentInteractionController *)controller{
    return self;
}

答案 1 :(得分:1)

首先验证该字符串并将其分配给URL,如下所示..

   NSString *strURLPath = [self trimString: path];
   NSURL *url = [NSURL fileURLWithPath:strURLPath];

使用我的波纹管方法......

-(NSString*) trimString:(NSString *)theString {
    if (theString != [NSNull null])
        theString = [theString stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]];
    return theString;
}

答案 2 :(得分:1)

它与给定的代码问题工作正常是在我的文件名称我也提供类似于ali.pdf的类型他们输入pdf所以它得到例外它现在工作正常当我使用文件名如下

 NSString*fileName=@"ali";

而不是

    NSString*fileName=@"ali.pdf";

答案 3 :(得分:0)

CGRect rect = [[UIScreen mainScreen] bounds];
    CGSize screenSize = rect.size;
    UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake(0,0,screenSize.width,screenSize.height)];

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

    [self.view addSubview:webView];