How to Open PDF File Using Uiwebview on iOS

Open PDF file using swift

If you simply want to view a PDF file you can load it into a UIWebView.

let url : NSURL! = NSURL(string: "http://developer.apple.com/iphone/library/documentation/UIKit/Reference/UIWebView_Class/UIWebView_Class.pdf")
webView.loadRequest(NSURLRequest(URL: url))

Swift 4.1 :

let url: URL! = URL(string: "http://developer.apple.com/iphone/library/documentation/UIKit/Reference/UIWebView_Class/UIWebView_Class.pdf")
webView.loadRequest(URLRequest(url: url))

If you'd like to achieve more, a good framework is PSPDFKit.

Cannot open PDF file using UIWebView in iOS8beta5

I found a workaround for viewing the PDF in WebView

// Create pdf path & url
NSString *path = [[NSBundle mainBundle] pathForResource:@"201" ofType:@"pdf"];
NSURL *targetURL = [NSURL fileURLWithPath:path];

// Load pdf in WebView
NSData *pdfData = [[NSData alloc] initWithContentsOfURL:targetURL];
[self.webView loadData:pdfData MIMEType:@"application/pdf" textEncodingName:@"utf-8" baseURL:nil];

How to Load Local PDF in UIWebView in Swift

Here you go:

if let pdf = NSBundle.mainBundle().URLForResource("myPDF", withExtension: "pdf", subdirectory: nil, localization: nil)  {
let req = NSURLRequest(URL: pdf)
let webView = UIWebView(frame: CGRectMake(20,20,self.view.frame.size.width-40,self.view.frame.size.height-40))
webView.loadRequest(req)
self.view.addSubview(webView)
}

Edit

The alternative is via NSData:

if let pdfURL = NSBundle.mainBundle().URLForResource("myPDF", withExtension: "pdf", subdirectory: nil, localization: nil),data = NSData(contentsOfURL: pdfURL), baseURL = pdfURL.URLByDeletingLastPathComponent  {
let webView = UIWebView(frame: CGRectMake(20,20,self.view.frame.size.width-40,self.view.frame.size.height-40))
webView.loadData(data, MIMEType: "application/pdf", textEncodingName:"", baseURL: baseURL)
self.view.addSubview(webView)
}

Apple make a point of advising you to not use .loadRequest for local HTML files, while not clearly extending this to other data types. So I've provided the NSData route above. If you wish to specify a textEncodingName it can be "utf-8", "utf-16", etc.

Edit: Swift 3

Here's a Swift 3 version of the code using, as Apple advise, WKWebView in place of UIWebView.

import UIKit
import WebKit

class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.

if let pdfURL = Bundle.main.url(forResource: "myPDF", withExtension: "pdf", subdirectory: nil, localization: nil) {
do {
let data = try Data(contentsOf: pdfURL)
let webView = WKWebView(frame: CGRect(x:20,y:20,width:view.frame.size.width-40, height:view.frame.size.height-40))
webView.load(data, mimeType: "application/pdf", characterEncodingName:"", baseURL: pdfURL.deletingLastPathComponent())
view.addSubview(webView)

}
catch {
// catch errors here
}

}
}

}

Accessing the PDF from Asset.xcassets (Swift 4)

if let asset = NSDataAsset(name: "myPDF") {
let url = Bundle.main.bundleURL
let webView = WKWebView(frame: CGRect(x:20,y:20,width:view.frame.size.width-40, height:view.frame.size.height-40))
webView.load(asset.data, mimeType: "application/pdf", characterEncodingName:"", baseURL:url)
view.addSubview(webView)
}

Can we open pdf file using UIWebView on iOS?

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.

How to display PDF files from remote location on UIWebView using Swift?

If the file is not in your app you should not use NSBundle.

let pdfUrl = NSURL(string: website)
let req = NSURLRequest(URL: pdfUrl)

I'm also not sure why you are adding the webView subview to the view. Shouldn't that be done somewhere else? Shouldn't you push a controller with the webview instead?

How to display NSData with PDF content in iOS UIWebView?

Got the answer for my question. The below line will do the magic.

 [webview loadData:PdfContent MIMEType:@"application/pdf" textEncodingName:@"utf-8" baseURL:nil];

How to display pdf on iOS

You can use a UIWebView to get the PDF from your bundle directly, no need to call an online web service.

Local File:

NSString *html = [NSString stringWithContentsOfFile:path1 encoding:NSUTF8StringEncoding error:nil];
[self.webView loadHTMLString:html baseURL:[NSURL fileURLWithPath:[[NSBundle mainBundle]bundlePath]]];

Remote File:

- (void) loadRemotePdf
{
CGRect rect = [[UIScreen mainScreen] bounds];
   CGSize screenSize = rect.size;
       
    UIWebView *myWebView = [[UIWebView alloc] initWithFrame:CGRectMake(0,0,screenSize.width,screenSize.height)];
        webView.autoresizesSubviews = YES;
        webView.autoresizingMask=(UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth);

   NSURL *myUrl = [NSURL URLWithString:@"http://www.mysite.com/test.pdf"];
   NSURLRequest *myRequest = [NSURLRequest requestWithURL:myUrl];
       
    [webView loadRequest:myRequest];

   [window addSubview: myWebView];
   [myWebView release];
       
}

How to open PDF in iOS not using UIWebView?

Option 1 :

        let theFileName = (self.my_object.my_pdf as NSString).lastPathComponent

let url = URL(string:self.my_object.my_pdf)
let task = URLSession.shared.dataTask(with: url!) { data, response, error in
guard error == nil else {
print(error!)
return
}

guard let data = data else {
print("Data is empty")
return
}

print(data)

do {
let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
let filePath = "\(documentsPath)/\(theFileName)"
let url = URL.init(fileURLWithPath: filePath)
try data.write(to: url)
self.documentController = UIDocumentInteractionController.init(url: url)
self.documentController.delegate = self
self.documentController.presentPreview(animated: true)
self.downloadBtn.action = #selector(self.downloadButtonTapped)
//self.documentController.presentOpenInMenu(from: self.downloadBtn, animated: true)

} catch let error as NSError {
self.downloadBtn.action = #selector(self.downloadButtonTapped)
print(error.localizedDescription)
}
}

task.resume()

Option 2:

it works only and after iOS 11.0+ && MacOS 10.4+

import PDFKit
let pdfView = PDFView()


pdfView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(pdfView)

pdfView.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor).isActive = true
pdfView.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor).isActive = true
pdfView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor).isActive = true
pdfView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor.topAnchor).isActive = true

guard let path = Bundle.main.url(forResource: "example", withExtension: "pdf") else { return }

if let document = PDFDocument(url: path) {
pdfView.document = document
}

Source : https://developer.apple.com/documentation/pdfkit

How do I make UIWebView show a pdf file from its own app?

Use pathForResource and fileURLWithPath:

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


Related Topics



Leave a reply



Submit