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
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
}
}
I have local pdf files in a document directory. My code calls each one to display using WKWebview or PDFViewer, but it only shows on an iPhone XR simulator, but not on any other simulator devices.
Any devices which are older than XR, it shows an error:
libMobileGestalt MobileGestalt.c:890: MGIsDeviceOneOfType is not supported on this platform.
Devices with XS, XS Max, it shows the error:
failed to open pdf ...
as seen in the code.
Does anyone know why?
I use Xcode 10.2.
Here is the code that I use for WKWebviewer
#IBOutlet weak var webView: WKWebView!
//only work on XR, don't know why
override func viewDidLoad() {
super.viewDidLoad()
let documentDir = FileManager.SearchPathDirectory.documentDirectory
let userDir = FileManager.SearchPathDomainMask.userDomainMask
let paths = NSSearchPathForDirectoriesInDomains(documentDir, userDir, true)
if let dirPath = paths.first
{
let pdfURL = URL(fileURLWithPath: dirPath).appendingPathComponent("my file.pdf")
do {
//only work in Xr
let data = try Data(contentsOf: pdfURL)
webView.load(data, mimeType: "application/pdf", characterEncodingName:"", baseURL: pdfURL.deletingPathExtension())
//not working for Xs, Xs Max... later iphone
//webView.loadFileURL(pdfURL, allowingReadAccessTo: pdfURL)
//webView.load(URLRequest(url:pdfURL))
//webView.loadFileURL(pdfURL, allowingReadAccessTo: pdfURL)
print("open pdf file....")
}
catch {
print("failed to open pdf \(dirPath)" )
}
return
}
and for PDFViewer:
let documentDir = FileManager.SearchPathDirectory.documentDirectory
let userDir = FileManager.SearchPathDomainMask.userDomainMask
let paths = NSSearchPathForDirectoriesInDomains(documentDir, userDir, true)
if let dirPath = paths.first
{
let pdfURL = URL(fileURLWithPath: dirPath).appendingPathComponent("myfile2.pdf")
view.addSubview(pdfView)
pdfView.autoresizesSubviews = true
pdfView.autoresizingMask = [.flexibleWidth, .flexibleHeight, .flexibleTopMargin, .flexibleLeftMargin]
pdfView.displayDirection = .vertical
//pdfView.autoScales = true
pdfView.displayMode = .singlePageContinuous
pdfView.displaysPageBreaks = true
if let document = PDFDocument(url: pdfURL) {
pdfView.document = document
}
pdfView.maxScaleFactor = 4.0
pdfView.minScaleFactor = pdfView.scaleFactorForSizeToFit
Matt helps me to find out the problem. Thank you Matt. Please see the comments. Each iOS device in simulator has different folder id. When you download to a device simulator document directory, do not expect it could find the same for another simulator device in the same document directory.
let url = NSURL (string: "https://i.stack.imgur.com/0LSmY.jpg");
let webViewInst: UIWebView = UIWebView()
let requestObj = NSURLRequest(url: url! as URL)
webViewInst.frame = self.view.bounds
webViewInst.loadRequest(requestObj as URLRequest);
webViewInst.delegate = self
webViewInst.scalesPageToFit = true
webViewInst.contentMode = .scaleAspectFit
self.view.addsubview(webViewInst)
This is working, but we need to scroll the webview to see full image in the web page. How to fix this?
How to show the full image fit to the view?
P.S, the image that mentioned in the above url is more than 3000 pixel in diomensions(3024x4032)
Try this one I have implemented it and working as you expected.
webView = WKWebView(frame: self.view.frame)
let urlString = "https://i.stack.imgur.com/0LSmY.jpg"
let url = URL(string: urlString)!
let request = URLRequest(url: url)
webView.load(request)
self.view.addSubview(webView)
self.view.sendSubview(toBack: webView)
I am rendering a local PDF in webView but it cuts off the right side of the PDF. Below is the code -
if let pdf = NSBundle.mainBundle().URLForResource("myPDF", withExtension: "pdf", subdirectory: nil, localization: nil) {
let req = NSURLRequest(URL: pdf)
let webView = UIWebView(frame: CGRectMake(0,60,self.view.frame.size.width,self.view.frame.size.height))
webView.scalesPageToFit = true
webView.loadRequest(req)
self.view.addSubview(webView)
}
Any help would be much appreciated.
Thanks!
Try this,
if let pdf = NSBundle.mainBundle().URLForResource("myPDF", withExtension: "pdf", subdirectory: nil, localization: nil) {
let req = NSURLRequest(URL: pdf)
let webView = UIWebView(frame: CGRectMake(0,60,self.view.frame.size.width,self.view.frame.size.height))
self.view.addSubview(webView)
webView.loadRequest(req)
}
Hope this will help :)
I got solution -
Just moved the code from viewDidLoad to viewWillAppear, And it resolved my issue :).
How can I add a PDF file for an app , where you click on a button to view the file & when you're done you get back to screen you were at?
If you simply want to view a PDF file you can load it into a 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))
If you'd like to achieve more, a good framework is PSPDFKit.
Apple added PDFKit framework in iOS 11
Add a UIView to your view controller and make it's class to 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
}
}
}
}
There are 4 display modes : singlePage, singlePageContinuous, twoUp, twoUpContinuous .
SWIFT 4+
If has to open file from local cache/Documentdiectory which has file path
Method 1: using 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
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
For Xcode 8.1 and Swift 3.0
Save the PDF file in any folder of your xcode.
Suppose the file name is '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.
you can use UIDocumentInteractionController to preview file in IOS.
In the view controller's file, add a property of type UIDocumentInteractionController
and implement a simple delegate method of it
self.documentInteractionController = UIDocumentInteractionController.init(URL: url)
self.documentInteractionController?.delegate = self
self.documentInteractionController?.presentPreviewAnimated(true)
func documentInteractionControllerViewControllerForPreview(controller: UIDocumentInteractionController) -> UIViewController {
return self
}
don't forget to add UIDocumentInteractionControllerDelegate in view controller's class
Check out PDFKit from IOS11
Here is an example of a view controller which implements PDFView from PDFKit.
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!)
}
}
SWIFT 5
An update to open the file from the Document directory (device) and present preview:
let urlFile = URL(string: pathToFile)
var documentInteractionController: UIDocumentInteractionController!
documentInteractionController = UIDocumentInteractionController.init(url: urlFile!)
documentInteractionController?.delegate = self
documentInteractionController?.presentPreview(animated: true)
And UIDocumentInteractionControllerDelegate:
extension ViewController: UIDocumentInteractionControllerDelegate {
func documentInteractionControllerViewControllerForPreview(_ controller: UIDocumentInteractionController) -> UIViewController {
return self
}
}
If you want to dismiss the document preview you can use:
documentInteractionController?.dismissPreview(animated: true)
You can use this code in Swift 4
Import PDFKit
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
}
You can use this UIViewController. It contains the share button for free:
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)
}
}
To use it:
let viewController = PDFWebViewController()
// the url can be a web url or a file url
viewController.pdfURL = url
self.navigationController?.pushViewController(viewController, animated: true)
You can also use Quick Look Framework from Apple.
It is very flexible.
You can show your PDF file with zoom feature.
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.
Please refer
this answer if you want detail description of using QuickLook.framework
A modernized version of Akila's answer, with the benefit that it is a drop in, ready to use UIViewController that you can integrate into your app.
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)
}
}
}
It creates the PDFView during viewDidLoad and sets it to use the view's frame
The URL for the PDF file is safely unwrapped from the bundle and then a PDFDocument is created, if possible
Some common settings are used. Adjust as needed
Finally, it adds the PDFView as a subview of the controller's view
//In 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)
}
}
if let url: URL = URL(string: "http://developer.apple.com/iphone/library/documentation/UIKit/Reference/UIWebView_Class/UIWebView_Class.pdf") {
webView.loadRequest(URLRequest(url: url)) }
let openLink = NSURL(string : 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 = UIStoryboard(
name: "Main",
bundle: nil
).instantiateViewController(withIdentifier: "PDFViewer") as! PDFViewer
port.strUrl = OtherContactorProfileVview.Result.CertificateList[index].CertificateFileLink
navigationController?.pushViewController(port, animated: true)
}