user10241787
user10241787

Reputation:

How to display pdf downloaded from internet in PDFKit?

I have successfully download pdf file from Internet and it is saved in documents directory. The url is as follows of the downloaded file

file:///Users/heetshah/Library/Developer/CoreSimulator/Devices/4BF83AAF-A910-46EB-AE76-91BC6BEED033/data/Containers/Data/Application/B4532805-2842-431F-B16C-C5E448C8366F/Documents/TPAFForm.pdf

I am trying to display it to PDFKit as follows.

let path = URL(fileURLWithPath: pdfUrl!)
if let document = PDFDocument(url: path) {
  pdfView.document = document
  pdfView.displayMode = .singlePageContinuous
  pdfView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
  pdfView.displaysAsBook = true
  pdfView.displayDirection = .vertical
  pdfView.autoScales = true
  pdfView.maxScaleFactor = 4.0
  pdfView.minScaleFactor = pdfView.scaleFactorForSizeToFit
}

I am not getting any error

I have went through bunch of stack overflow posts and it is displaying the same solution as above but it does not work in my case. I also tried following solution but it does not work

if let path = Bundle.main.path(forResource: pdfUrl, ofType: "pdf") {
            let url = URL(fileURLWithPath: path)
            if let pdfDocument = PDFDocument(url: url) {..

Following is my code to download the file

func downloadPDF(pdfUrl: String?,fileName: String,completionHandler:@escaping(String,Bool) -> ()){
        let destinationPath: DownloadRequest.DownloadFileDestination = {
            _,_ in
            let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
            let fileURL = documentsURL.appendingPathComponent("\(fileName).pdf")
            return (fileURL,[.removePreviousFile,.createIntermediateDirectories])
        }

        if let pdfUrl = pdfUrl {
            Alamofire.download(pdfUrl, to: destinationPath).downloadProgress { (progress) in

            }.responseData { (response) in
                switch response.result{
                case .success:
                    if response.destinationURL != nil,let filePath = response.destinationURL?.absoluteString{
                        completionHandler(filePath,true)
                    }
                    break
                case .failure:
                    completionHandler("Something went wrong",false)
                    break
                }
            }
        }
    }

I am using Alamofire to download the file. There constraint for my PDFView are proper as I am able to display an online url pdf in my preview but I need to download the pdf locally first and then display it in my pdf view

Upvotes: 0

Views: 3820

Answers (1)

matt
matt

Reputation: 534903

Since you have not shown sufficient code to debug the problem, here is complete code for doing what you describe, and you can debug your problem by comparing your code to mine:

import UIKit
import PDFKit

class ViewController: UIViewController {

    let pdfurl = URL(string:"https://www.apeth.com/rez/release.pdf")!
    let pdffileurl : URL = {
        let fm = FileManager.default
        let docsurl = try! fm.url(
            for: .documentDirectory, in: .userDomainMask, 
            appropriateFor: nil, create: true)
        return docsurl.appendingPathComponent("mypdf.pdf")
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        let sess = URLSession.shared
        sess.downloadTask(with: self.pdfurl) { (url, resp, err) in
            if let url = url {
                let fm = FileManager.default
                try? fm.removeItem(at: self.pdffileurl)
                try? fm.moveItem(at: url, to: self.pdffileurl)
                DispatchQueue.main.async {
                    self.displayPDF()
                }
            }
        }.resume()
    }

    func displayPDF() {
        let pdfview = PDFView(frame:self.view.bounds)
        pdfview.autoresizingMask = [.flexibleWidth, .flexibleHeight]
        pdfview.autoScales = true
        self.view.addSubview(pdfview)
        let doc = PDFDocument(url: self.pdffileurl)
        pdfview.document = doc
    }

}

Upvotes: 4

Related Questions