67

How can I add a PDF file for an app , where you click on a button to view the file & when you're done you get back to screen you were at?

Jack
  • 13,571
  • 6
  • 76
  • 98
user3706773
  • 2,989
  • 3
  • 15
  • 9

14 Answers14

75

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.

Sunil Targe
  • 7,251
  • 5
  • 49
  • 80
Jasper Blues
  • 28,258
  • 22
  • 102
  • 185
  • 6
    UIWebView can load a local PDF. Instead use `[NSURL fileURLWithPath:strURLPath];` . . the path will be either your documents directory or your resource bundle. . There's also a method on UIWebView to load data, so you could feed it an NSData object. (Streaming from file is probably better for memory usage though). – Jasper Blues Nov 12 '14 at 10:11
  • If in resources directory: http://stackoverflow.com/questions/6398937/getting-a-list-of-files-in-the-resources-folder-ios (similar story for documents dir). . . build NSURL from string. – Jasper Blues Nov 12 '14 at 10:24
  • is PSPDFKit suggested by Jasper is free? – jishnu bala Oct 12 '15 at 06:38
  • I've never tried it, but heard it is popular. On the website it looks like its a paid product, however the actual price is not clear! – Jasper Blues Oct 12 '15 at 06:40
  • 2
    Starting in iOS 8.0 and OS X 10.10, use WKWebView to add web content to your app. Do not use UIWebView or WebView. – MosTwanTedT Dec 05 '20 at 21:23
  • @MosTwanTedT Feel free to edit the answer with current best approach – Jasper Blues Dec 06 '20 at 02:00
67

Apple added PDFKit framework in iOS 11

Add a UIView to your view controller and make it's class to PDFView

enter image description here

import UIKit
import PDFKit

class ViewController: UIViewController {

    @IBOutlet var pdfView: PDFView!

    override func viewDidLoad() {
        super.viewDidLoad()

        if let path = Bundle.main.path(forResource: "sample", ofType: "pdf") {
            if let pdfDocument = PDFDocument(url: URL(fileURLWithPath: path)) {
                pdfView.displayMode = .singlePageContinuous
                pdfView.autoScales = true
                pdfView.displayDirection = .vertical
                pdfView.document = pdfDocument
            }
        }
    }
}

There are 4 display modes : singlePage, singlePageContinuous, twoUp, twoUpContinuous .

rmaddy
  • 314,917
  • 42
  • 532
  • 579
ajw
  • 2,568
  • 23
  • 27
26

SWIFT 4+

If has to open file from local cache/Documentdiectory which has file path

Method 1: using UIDocumentInteractionController

class ViewController: UIViewController,UIDocumentInteractionControllerDelegate {
   //let path =  Bundle.main.path(forResource: "Guide", ofType: ".pdf")!
    let dc = UIDocumentInteractionController(url: URL(fileURLWithPath: path))
    dc.delegate = self
    dc.presentPreview(animated: true)
}

//MARK: UIDocumentInteractionController delegates
func documentInteractionControllerViewControllerForPreview(_ controller: UIDocumentInteractionController) -> UIViewController {
    return self//or use return self.navigationController for fetching app navigation bar colour
}

Method 2: using WebView

let webview = WKWebView(frame: UIScreen.main.bounds)
view.addSubview(webview)
webview.navigationDelegate = self
webview.load(URLRequest(url: URL(fileURLWithPath: path)))//URL(string: "http://") for web URL
Olcay Ertaş
  • 5,987
  • 8
  • 76
  • 112
Jack
  • 13,571
  • 6
  • 76
  • 98
18

For Xcode 8.1 and Swift 3.0

Save the PDF file in any folder of your xcode. Suppose the file name is 'Filename.pdf'

if let pdf = Bundle.main.url(forResource: "Filename", withExtension: "pdf", subdirectory: nil, localization: nil)  {
    let req = NSURLRequest(url: pdf)
    yourWebViewOutletName.loadRequest(req as URLRequest)        
}

Same will apply if you want to open any html file.

Olcay Ertaş
  • 5,987
  • 8
  • 76
  • 112
Anil shukla
  • 277
  • 3
  • 10
14

Check out PDFKit from IOS11

Here is an example of a view controller which implements PDFView from PDFKit.

import UIKit
import PDFKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        // Add PDFView to view controller.
        let pdfView = PDFView(frame: self.view.bounds)
        self.view.addSubview(pdfView)

        // Fit content in PDFView.
        pdfView.autoScales = true

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

}
Stewart Evans
  • 1,416
  • 1
  • 12
  • 17
13

you can use UIDocumentInteractionController to preview file in IOS. In the view controller's file, add a property of type UIDocumentInteractionController

and implement a simple delegate method of it

self.documentInteractionController = UIDocumentInteractionController.init(URL: url)
self.documentInteractionController?.delegate = self
self.documentInteractionController?.presentPreviewAnimated(t‌​rue) 

func documentInteractionControllerViewControllerForPreview(controller: UIDocumentInteractionController) -> UIViewController {
    return self
}

don't forget to add UIDocumentInteractionControllerDelegate in view controller's class

pacification
  • 5,838
  • 4
  • 29
  • 51
Shan Shafiq
  • 1,018
  • 10
  • 10
  • 1
    self.documentInteractionController = UIDocumentInteractionController.init(URL: url) self.documentInteractionController?.delegate = self self.documentInteractionController?.presentPreviewAnimated(true) – Shan Shafiq Feb 08 '16 at 07:16
  • It's useless in this case. "Preview" should be used for preview - in small views, but not for "opening" pdf. – Alexander Volkov May 17 '20 at 11:50
11

SWIFT 5

An update to open the file from the Document directory (device) and present preview:

let urlFile = URL(string: pathToFile)
var documentInteractionController: UIDocumentInteractionController!    
documentInteractionController = UIDocumentInteractionController.init(url: urlFile!)
documentInteractionController?.delegate = self
documentInteractionController?.presentPreview(animated: true)

And UIDocumentInteractionControllerDelegate:

extension ViewController: UIDocumentInteractionControllerDelegate {
    func documentInteractionControllerViewControllerForPreview(_ controller: UIDocumentInteractionController) -> UIViewController {
        return self
    }
}

If you want to dismiss the document preview you can use:

documentInteractionController?.dismissPreview(animated: true)
Olcay Ertaş
  • 5,987
  • 8
  • 76
  • 112
Alix Huerta
  • 231
  • 3
  • 4
6

You can use this UIViewController. It contains the share button for free:

import UIKit
import PDFKit

class PDFWebViewController: UIViewController {
    var pdfURL: URL!
    
    private var pdfView: PDFView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.edgesForExtendedLayout = []
                
        self.setPDFView()
        self.fetchPDF()
    }
    
    private func setPDFView() {
        DispatchQueue.main.async {
            self.pdfView = PDFView(frame: self.view.bounds)
            
            self.pdfView.maxScaleFactor = 3;
            self.pdfView.minScaleFactor = self.pdfView.scaleFactorForSizeToFit;
            self.pdfView.autoScales = true;
            self.pdfView.autoresizingMask = [.flexibleHeight, .flexibleWidth]
            
            self.view.addSubview(self.pdfView)
        }
    }
    
    private func fetchPDF() {
        DispatchQueue.global(qos: .userInitiated).async {
            if let data = try? Data(contentsOf: self.pdfURL), let document = PDFDocument(data: data) {
                DispatchQueue.main.async {
                    self.pdfView.document = document
                    self.addShareBarButton()
                }
            }
        }
    }
    
    private func addShareBarButton() {
        let barButtonItem = UIBarButtonItem(barButtonSystemItem: .action,
                                            target: self,
                                            action: #selector(self.presentShare))
        barButtonItem.tintColor = .white
        self.navigationItem.rightBarButtonItem = barButtonItem
    }
    
    @objc private func presentShare() {
        guard let pdfDocument = self.pdfView.document?.dataRepresentation() else { return }
        
        let activityViewController = UIActivityViewController(activityItems: [pdfDocument], applicationActivities: nil)
        activityViewController.popoverPresentationController?.barButtonItem = self.navigationItem.rightBarButtonItem
        
        self.present(activityViewController, animated: true)
    }
}

To use it:

let viewController = PDFWebViewController()

// the url can be a web url or a file url
viewController.pdfURL = url
        
self.navigationController?.pushViewController(viewController, animated: true)
pableiros
  • 14,932
  • 12
  • 99
  • 105
5

You can use this code in Swift 4

  1. Import PDFKit
  2. Copy this code

    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).isActive = true
    
    guard let path = Bundle.main.url(forResource: "test", withExtension: "pdf") else { return }
    
    if let document = PDFDocument(url: path) {
        pdfView.document = document
    }
    
Eric Aya
  • 69,473
  • 35
  • 181
  • 253
Enamul Haque
  • 823
  • 1
  • 14
  • 24
3

You can also use Quick Look Framework from Apple.

It is very flexible.

You can show your PDF file with zoom feature.

Also you have support for all other types (like png, jpg, docx, txt, rtf, xlsx, zip, mov, etc) of files and it is very easy to use.

Please refer this answer if you want detail description of using QuickLook.framework

Prashant Gaikwad
  • 3,493
  • 1
  • 24
  • 26
2

A modernized version of Akila's answer, with the benefit that it is a drop in, ready to use UIViewController that you can integrate into your app.

import UIKit
import PDFKit

final class PDFViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()

        let pdfView = PDFView(frame: view.frame)
        
        title = "Your_title_here"
        
        if let url = Bundle.main.url(forResource: "document_name_here", withExtension: "pdf"),
            let pdfDocument = PDFDocument(url: url) {
            pdfView.displayMode = .singlePageContinuous
            pdfView.autoScales = true
            pdfView.displayDirection = .vertical
            pdfView.document = pdfDocument
            
            view.addSubview(pdfView)
        }
    }
}
  • It creates the PDFView during viewDidLoad and sets it to use the view's frame
  • The URL for the PDF file is safely unwrapped from the bundle and then a PDFDocument is created, if possible
  • Some common settings are used. Adjust as needed
  • Finally, it adds the PDFView as a subview of the controller's view
CodeBender
  • 35,668
  • 12
  • 125
  • 132
1

//In Swift 5

    class PDFBookViewController: UIViewController, PDFViewDelegate {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        addPDFView()  
    }
    
    private func addPDFView() {
        let pdfView = PDFView()
        pdfView.translatesAutoresizingMaskIntoConstraints = false
        pdfContenerView.addSubview(pdfView)
    
        pdfView.leadingAnchor.constraint(equalTo: pdfContenerView.safeAreaLayoutGuide.leadingAnchor).isActive = true
        pdfView.trailingAnchor.constraint(equalTo: pdfContenerView.safeAreaLayoutGuide.trailingAnchor).isActive = true
        pdfView.topAnchor.constraint(equalTo: pdfContenerView.safeAreaLayoutGuide.topAnchor).isActive = true
        pdfView.bottomAnchor.constraint(equalTo: pdfContenerView.safeAreaLayoutGuide.bottomAnchor).isActive = true
        
        pdfView.autoScales = true
        pdfView.displayMode = .singlePageContinuous
        pdfView.displayDirection = .vertical
        
        ///Open pdf with help of FileManager URL
        if let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {
            let bookWithPdf = "\(bookname).pdf"
            let fileURL = dir.appendingPathComponent(bookWithPdf)
            let document = PDFDocument(url: fileURL)
            pdfView.document = document
        } 
  @IBAction func backButtonPressed(_ sender: Any) {
            navigationController?.popViewController(animated: true)
        } 
}
Sambit Das
  • 131
  • 1
  • 5
1
if let url: URL = URL(string: "http://developer.apple.com/iphone/library/documentation/UIKit/Reference/UIWebView_Class/UIWebView_Class.pdf") {
webView.loadRequest(URLRequest(url: url)) }
Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
santhosh
  • 11
  • 1
-1
let openLink = NSURL(string : OtherContactorProfileVview.Result.CertificateList[index].CertificateFileLink)

if #available(iOS 9.0, *) {
    let svc = SFSafariViewController(url: openLink! as URL)
    present(svc, animated: true, completion: nil)
} else {
    let port = UIStoryboard(
        name: "Main",
        bundle: nil
    ).instantiateViewController(withIdentifier: "PDFViewer") as! PDFViewer
    port.strUrl = OtherContactorProfileVview.Result.CertificateList[index].CertificateFileLink
    navigationController?.pushViewController(port, animated: true)
}
Olcay Ertaş
  • 5,987
  • 8
  • 76
  • 112
Gaurav Gudaliya
  • 131
  • 1
  • 1
  • 9