AL-Maher
AL-Maher

Reputation: 25

How to display a single page of a multi-document PDF pages using SWIFT

I want to display a single page for a chosen PDF file even if the PDF has more than one page.

So that only a single PDF page is displayed according to the selected page number.

I am writing this code:

    let path = NSURL(fileURLWithPath: Bundle.main.path(forResource: "PDFName", ofType: "pdf")!)
    let request = NSURLRequest(url: path as URL)
    webView.loadRequest(request as URLRequest)

But that displays all pages of a document. I want to show only one page by page number?

Upvotes: 1

Views: 2296

Answers (1)

Anbu.Karthik
Anbu.Karthik

Reputation: 82766

for step by step implementation , you can get the tutorial here1 and here2

class ReaderViewController: UIViewController, UIDocumentInteractionControllerDelegate

 func loadDocUsingDocInteractionController() {

if let fileURL = NSBundle.mainBundle().pathForResource("PDFName", ofType: "pdf") { // Use if let to unwrap to fileURL variable if file exists
    let docInteractionController = UIDocumentInteractionController(URL: NSURL(fileURLWithPath: fileURL)!)
    docInteractionController.delegate = self
    docInteractionController.presentPreviewAnimated(true)
}
}

// Return the view controller from which the    UIDocumentInteractionController will present itself.
func documentInteractionControllerViewControllerForPreview(controller: UIDocumentInteractionController) -> UIViewController {
return self
}

swift3

class ViewController:UIViewController,UIDocumentInteractionControllerDelegate

and call the function as like

@IBAction func btnOpenModal(_ sender: UIButton) {

  //  var button: UIButton? = (sender as? UIButton)
    let URLName: URL? = Bundle.main.url(forResource: "sample", withExtension: "pdf")
    if URLName != nil {
        // Initialize Document Interaction Controller
        let  documentInteractionController: UIDocumentInteractionController = UIDocumentInteractionController(url: URLName!)
        // Configure Document Interaction Controller
        documentInteractionController.delegate = self
        // Present Open In Menu
        documentInteractionController.presentOpenInMenu(from: sender .frame, in: self.view, animated: true)
    }
}

func documentInteractionControllerViewControllerForPreview(_ controller: UIDocumentInteractionController) -> UIViewController {

    return self
}

Upvotes: 1

Related Questions