使用swift打开PDF文件

use*_*773 35 iphone ios swift

如何为应用程序添加PDF文件,在此处单击按钮查看文件?完成后,您将返回到您所在的屏幕?

Jas*_*ues 60

如果您只想查看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))
Run Code Online (Sandbox Code Playgroud)

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))
Run Code Online (Sandbox Code Playgroud)

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

  • UIWebView可以加载本地PDF.而是使用`[NSURL fileURLWithPath:strURLPath];`..路径将是您的文档目录或资源包..UIWebView上还有一个加载数据的方法,因此您可以为它提供一个NSData对象.(尽管如此,从文件流式传输可能更适合内存使用). (5认同)
  • 从 iOS 8.0 和 OS X 10.10 开始,使用 WKWebView 将 Web 内容添加到您的应用程序。不要使用 UIWebView 或 WebView。 (3认同)

Aki*_*ala 31

Apple在其中添加了PDFKit框架iOS 11

将UIView添加到视图控制器并将其作为PDFView的类

在此输入图像描述

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
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

有4种显示模式:singlePage,singlePageContinuous,twoUp,twoUpContinuous.


Jac*_*ack 23

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
 }
Run Code Online (Sandbox Code Playgroud)

方法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
Run Code Online (Sandbox Code Playgroud)


Ani*_*kla 15

对于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)        
  }
Run Code Online (Sandbox Code Playgroud)

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


小智 14

您可以使用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
}
Run Code Online (Sandbox Code Playgroud)

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


Ste*_*ans 8

退房PDFKit从IOS11

这是从 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!)
    }

}
Run Code Online (Sandbox Code Playgroud)


小智 7

快速 5

文档目录(设备)打开文件并显示预览的更新:

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

和 UIDocumentInteractionControllerDelegate:

extension ViewController: UIDocumentInteractionControllerDelegate {
    func documentInteractionControllerViewControllerForPreview(_ controller: UIDocumentInteractionController) -> UIViewController {
        return self
    }
}
Run Code Online (Sandbox Code Playgroud)

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

documentInteractionController?.dismissPreview(animated: true)
Run Code Online (Sandbox Code Playgroud)


pab*_*ros 6

你可以用这个UIViewController。它包含share button免费的:

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)
    }
}
Run Code Online (Sandbox Code Playgroud)

使用方法:

let viewController = PDFWebViewController()

// the url can be a web url or a file url
viewController.pdfURL = url
        
self.navigationController?.pushViewController(viewController, animated: true)
Run Code Online (Sandbox Code Playgroud)


Ena*_*que 5

您可以在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
    }
    
    Run Code Online (Sandbox Code Playgroud)