Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we open pdf file using UIWebView on iOS?

Tags:

ios

pdf

uiwebview

Can we open the pdf file from UIWebView?

like image 801
MohammedYakub Moriswala Avatar asked May 14 '10 06:05

MohammedYakub Moriswala


People also ask

How do I open a PDF in Swift IOS?

let fileURL = Bundle. main. url(forResource: "Sample", withExtension: "pdf") pdfView. document = PDFDocument(url: fileURL!) } }

Can we open PDF in WebView in android?

Opening a PDF file in Android using WebView All you need to do is just put WebView in your layout and load the desired URL by using the webView. loadUrl() function. Now, run the application on your mobile phone and the PDF will be displayed on the screen.


2 Answers

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:

Objective-C

UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake(10, 10, 200, 200)];  NSURL *targetURL = [NSURL URLWithString:@"https://www.example.com/document.pdf"]; NSURLRequest *request = [NSURLRequest requestWithURL:targetURL]; [webView loadRequest:request];  [self.view addSubview:webView]; 

Swift

let webView = UIWebView(frame: CGRect(x: 10, y: 10, width: 200, height: 200))  let targetURL = NSURL(string: "https://www.example.com/document.pdf")! // This value is force-unwrapped for the sake of a compact example, do not do this in your code let request = NSURLRequest(URL: targetURL) webView.loadRequest(request)  view.addSubview(webView) 

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

Objective-C

UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake(10, 10, 200, 200)];  NSURL *targetURL = [[NSBundle mainBundle] URLForResource:@"document" withExtension:@"pdf"]; NSURLRequest *request = [NSURLRequest requestWithURL:targetURL]; [webView loadRequest:request];  [self.view addSubview:webView]; 

Swift

let webView = UIWebView(frame: CGRect(x: 10, y: 10, width: 200, height: 200))  let targetURL = NSBundle.mainBundle().URLForResource("document", withExtension: "pdf")! // This value is force-unwrapped for the sake of a compact example, do not do this in your code let request = NSURLRequest(URL: targetURL) webView.loadRequest(request)  view.addSubview(webView) 

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

like image 200
alleus Avatar answered Nov 15 '22 23:11

alleus


UIWebviews can also load the .pdf using loadData method, if you acquire it as NSData:

[self.webView loadData:self.pdfData                MIMEType:@"application/pdf"        textEncodingName:@"UTF-8"                 baseURL:nil]; 
like image 27
Yunus Nedim Mehel Avatar answered Nov 15 '22 23:11

Yunus Nedim Mehel