ios 使用swift打开PDF文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26883816/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 03:35:50  来源:igfitidea点击:

Open PDF file using swift

iosiphoneswift

提问by user3706773

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

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

回答by Jasper Blues

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

如果您只是想查看 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 :

斯威夫特 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.

如果你想实现更多,一个好的框架是PSPDFKit

回答by Akila Wasala

Apple added PDFKitframework in iOS 11

苹果在中添加了PDFKit框架iOS 11

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

将 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
            }
        }
    }
}

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

有 4 种显示模式:singlePagesinglePageContinuoustwoUptwoUpContinuous

回答by Hyman

SWIFT 4+

斯威夫特 4+

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

如果必须从具有文件路径的本地缓存/文档目录中打开文件

Method 1: using UIDocumentInteractionController

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

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

回答by Anil shukla

For Xcode 8.1 and Swift 3.0

对于 Xcode 8.1 和 Swift 3.0

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

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

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

如果您想打开任何 html 文件,同样适用。

回答by Shan Shafiq

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

您可以使用 UIDocumentInteractionController 在 IOS 中预览文件。在视图控制器的文件中,添加类型为 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 UIDocumentInteractionControllerDelegatein view controller's class

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

回答by Stewart Evans

Check out PDFKitfrom IOS11

退房PDFKit从IOS11

Here is an example of a view controller which implements PDFView from 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!)
    }

}

回答by Enamul Haque

You can use this code in Swift 4

您可以在 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
    }
    
  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
    }
    

回答by Prashant Gaikwad

You can also use Quick Look Framework from Apple.

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

It is very flexible.

它非常灵活。

You can show your PDF file with zoom feature.

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

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.

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

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

请参考 这个答案如果你想要使用 QuickLook.framework 的详细描述

回答by Alix Huerta

SWIFT 5

快速 5

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

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

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

And UIDocumentInteractionControllerDelegate:

和 UIDocumentInteractionControllerDelegate:

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

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

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

self.documentInteractionController?.dismissPreview(animated: true)

回答by Gaurav Gudaliya

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)

        }