Yakub Moriswala Yakub Moriswala - 4 months ago 55
iOS Question

iPhone : can we open pdf file using UIWebView?

Can we open the pdf file from UIWebView ?

If any one has implemented this then please help me.

Any code snippet or any weblink would help.

Answer

Yes, this can be done with the UIWebView.

If you are trying to display a PDF file residing on a server somewhere, you can simply load it in your web view directly:

UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake(10, 10, 200, 200)];

NSURL *targetURL = [NSURL URLWithString:@"http://developer.apple.com/iphone/library/documentation/UIKit/Reference/UIWebView_Class/UIWebView_Class.pdf"];
NSURLRequest *request = [NSURLRequest requestWithURL:targetURL];
[webView loadRequest:request];

[self.view addSubview:webView];
//[webView release]; //deprecated for newer iOS 

Or if you have a PDF file bundled with your application (in this example named "document.pdf"):

UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake(10, 10, 200, 200)];

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

[self.view addSubview:webView];
//[webView release]; //deprecated for newer iOS 

You can find more information here: Technical QA1630: Using UIWebView to display select document types.