使用swift打开PDF文件

时间:2014-11-12 09:48:06

标签: ios iphone swift

如何为应用添加 PDF文件,点击按钮查看文件&当你完成后,你会回到你所在的屏幕上?

12 个答案:

答案 0 :(得分:52)

如果您只是想查看PDF文件,可以将其加载到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))

如果你想获得更多,一个好的框架是PSPDFKit

答案 1 :(得分:23)

Apple在iOS 11

中添加了PDFKit框架

将UIView添加到视图控制器并将其设为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
            }
        }
    }
}

有4种显示模式:singlePagesinglePageContinuoustwoUptwoUpContinuous

答案 2 :(得分:18)

SWIFT 4 +

如果必须从具有文件路径的本地缓存/ Documentdiectory打开文件

方法1:使用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
 }

方法2:使用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

答案 3 :(得分:14)

适用于Xcode 8.1和Swift 3.0

将PDF文件保存在xcode的任何文件夹中。 假设文件名是' 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)        
  }

如果要打开任何html文件,则同样适用。

答案 4 :(得分:13)

您可以使用UIDocumentInteractionController在IOS中预览文件。 在视图控制器的文件中,添加UIDocumentInteractionController类型的属性

并实现一个简单的委托方法

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

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

不要忘记在视图控制器的课程中添加UIDocumentInteractionControllerDelegate

答案 5 :(得分:4)

SWIFT 5

更新以从 Document 目录(设备)打开文件并显示预览:

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

和UIDocumentInteractionControllerDelegate:

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

如果要关闭文档预览,可以使用:

self.documentInteractionController?.dismissPreview(animated: true)

答案 6 :(得分:2)

您也可以使用Apple的Quick Look Framework。

非常灵活。

您可以使用缩放功能显示PDF文件。

此外,您还支持文件的所有其他类型(如png,jpg,docx,txt,rtf,xlsx,zip,mov等),并且非常易于使用。

请参考 this如果您想要使用QuickLook.framework

的详细说明,请回答

答案 7 :(得分:2)

您可以在Swift 4中使用此代码

  1. 导入PDFKit
  2. 复制此代码

    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
    }
    

答案 8 :(得分:1)

从IOS11中检出PDFKit

这是一个视图控制器的示例,它实现了PDFKit中的PDFView。

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!)
    }

}

答案 9 :(得分:0)

let openLink = NSURL(string : self.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 : PDFViewer = UIStoryboard.init(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "PDFViewer") as! PDFViewer
            port.strUrl = self.OtherContactorProfileVview.Result.CertificateList[index].CertificateFileLink
            self.navigationController?.pushViewController(port, animated: true)

        }

答案 10 :(得分:0)

Akila答案的现代化版本,它的优点是易于使用的UIViewController,您可以将其集成到您的应用中。

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)
        }
    }
}
  • 它在PDFView期间创建viewDidLoad并将其设置为使用视图的框架
  • 将PDF文件的URL从分发包中安全地解包,然后创建一个PDFDocument(如果可能)
  • 使用了一些常用设置。根据需要进行调整
  • 最后,它将PDFView添加为控制器的view的子视图

答案 11 :(得分:0)

//在 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)
        } 
}