Rendering Local PDF in webView cuts off the right side - ios

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 :).

Related

How I can show/display pdf document to full screen on pdfView?

I took pdfView, and I am trying to load pdf document on this pdfView. Pdf is not displaying/showing full screen w.r.t its pdfView as I added in storyboard. It has some gaps from top and bottom. (see the gray colour in pdf)
Here is the screenshot,
Here is the code I wrote for this,
func loadPdf(documentsURL:String){
if let pdfDocument = self.createPdfDocument(forFileName: documentsURL) {
self.pdfView.document = pdfDocument
pdfView.autoresizesSubviews = true
pdfView.autoresizingMask = [.flexibleWidth, .flexibleHeight, .flexibleTopMargin, .flexibleLeftMargin]
pdfView.displayDirection = .vertical
pdfView.autoScales = true
pdfView.displayMode = .singlePage//.singlePageContinuous
pdfView.displaysPageBreaks = true
pdfView.maxScaleFactor = 4.0
pdfView.minScaleFactor = pdfView.scaleFactorForSizeToFit
pdfView.usePageViewController(true, withViewOptions: [:])
self.pdfView.backgroundColor = UIColor.gray
}
}
How I can remove that extra space from top and bottom and make/show/display that pdf document to full to screen w.r.t pdfView which I added in storyboard that same size.
Any solution for this?
Here is the complete project
You can use webView for show .pdf on fullscreen you can show url and local file both
let url : NSURL! = NSURL(string: "http://developer.apple.com/iphone/library/documentation/UIKit/Reference/UIWebViw_Class/UIWebView_Class.pdf")
webView.loadRequest(NSURLRequest(URL: url))
and for local file you can use
let pdf = NSBundle.mainBundle().URLForResource("myPDF", withExtension: "pdf", subdirectory: nil, localization: nil)
let req = NSURLRequest(URL: pdf)
webView.loadRequest(req)

Why WKWebView is not loading pdf in iOS using swift?

I am using WKWebView to preview files from web url but some url are opened some are not. I don't know the reason why it is happening the urls are seeming identical but the url which is not getting loaded in WKWebView is getting downloaded in safari rather than opening.
working url:
https://test.store.digiboxx.com:9000/9d2830d7cdec4de2/mayavati/413780_2CB2E888-CCE2-474D-8549-00270F92C6F0_New_pfd.pdf?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=asdklhfgdefyu%2F20201220%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=20201220T131747Z&X-Amz-Expires=604800&X-Amz-SignedHeaders=host&X-Amz-Signature=204841a52ddfc4d003f4b0bea45488b45a347fcd8e694011c9de4680afcebe9c
Problematic url: https://test.store.digiboxx.com:9000/9d2830d7cdec4de2/mayavati/F6685A44-E65F-4A6F-9E8A-34DA333C3E2F_New_pfd.pdf?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=asdklhfgdefyu%2F20201220%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=20201220T131840Z&X-Amz-Expires=604800&X-Amz-SignedHeaders=host&X-Amz-Signature=85efaa80b4e53a47869c82b4dbe64c9bfa6417991184abf69891d71a19a986a9
webView = WKWebView(frame: otherDocumentView.bounds, configuration: WKWebViewConfiguration())
self.webView.navigationDelegate = self
webView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
self.otherDocumentView.addSubview(webView)
let myRequest = NSURLRequest(url: NSURL(string: fileURL)! as URL)
webView.load(myRequest as URLRequest)
if let pdf = NSBundle.mainBundle().URLForResource("myPDF", withExtension:
"pdf", subdirectory: nil, localization: nil) {
let req = NSURLRequest(URL: pdf)
let webView = UIWebView(frame: CGRectMake(20,20,self.view.frame.size.width-40,self.view.frame.size.height-40))
webView.loadRequest(req)
self.view.addSubview(webView)
}

Creating a custom webview from scratch

I am in a situation where I want more flexibility for webview than the offered by UIWebview and not at all by WKWebview. Things like customizing web request before start eg sending headers and redirections. Also as we know UIWebview officially deprecated now in iOS 12.
I'm looking forward to a generic webview now, I know its possible as open source examples say Firefox for iOS.
If you've been using any of your projects or know please tell me. Or if you can give me some information how can this be achieved or any tutorails links would be helpful.
Declare the WebView object
var webView: WKWebView!
//Load the data in webView
func loadUrl() {
var webView : WKWebView!
let script: WKUserScript = WKUserScript(source: source, injectionTime: .atDocumentEnd, forMainFrameOnly: true)
let userContentController: WKUserContentController = WKUserContentController()
let configuration = WKWebViewConfiguration()
configuration.userContentController = userContentController
userContentController.addUserScript(script)
webView = WKWebView(frame: CGRect.zero, configuration: configuration)
webView.uiDelegate = self
webView.navigationDelegate = self
webView.allowsLinkPreview = true
//Load the Data from URL
let url = URL(string: "Your URL")
var urlRequest = URLRequest(url: url! as URL)
urlRequest.setValue("application/json", forHTTPHeaderField: "Accept")
urlRequest.setValue("user-agent", forHTTPHeaderField: "User-Agent")
webView.load(urlRequest)
//Load the Data from local HTML
do {
guard let filePath = Bundle.main.path(forResource: "Your-HTML-File", ofType: "html")
else {
print ("FILE READING ERROR")
return
}
//get the content of HTML File
let contents = try String(contentsOfFile: filePath , encoding: .utf8)
webView.loadHTMLString(contents, baseURL:URL(fileURLWithPath: Bundle.main.bundlePath))
}
catch {
print ("FILE HTML ERROR")
}
}
//Delegate Method that called when webView finish Loading.
//You can apply css or style here
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
///Local CSS File
guard let path = Bundle.main.path(forResource: "Local-CSS-File", ofType: "css") else { return }
let script = "var head = document.getElementsByTagName('head')[0];var link = document.createElement('link');link.rel = 'stylesheet';link.type = 'text/css';link.href = '\(path)';link.media = 'all';head.appendChild(link);"
webView.evaluateJavaScript(script) {(result, error) in
if let error = error {
print(error)
}
}
//External CSS File
let externalCSSLink = "your-css-file-url"
let script2 = "var head = document.getElementsByTagName('head')[0];var link = document.createElement('link');link.rel = 'stylesheet';link.type = 'text/css';link.href = '\(externalCSSLink)';link.media = 'all';head.appendChild(link);"
webView.evaluateJavaScript(jsString1) {(result, error) in
if let error = error {
print(error)
}
}
}

UIWebview show full page with image

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)

Loading PDF From Documents URL

I seem to be having issues while loading a PDF to my WebView in Swift.
Printing out all the files in the Documents directory results in:
file:///Users/adriandavidsmith/Library/Developer/CoreSimulator/Devices/B537EBE4-14AE-439A-B84B-31342E233367/data/Containers/Data/Application/E791BF20-CC53-4FBB-B34A-F73CED74EB5D/Documents/DOCUMENT.pdf
However, when I attempt to load that file into a WebView nothing gets shown. As if it is unable to find the file.
if let pdf = NSBundle.mainBundle().URLForResource("DOCUMENT", withExtension: "pdf", subdirectory: "Documents", localization: nil){
let req = NSURLRequest(URL: pdf)
webView.loadRequest(req)
Any thoughts/ideas?
Swift 3 compatible
var pdfURL = (FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)).last! as URL
pdfURL = pdfURL.appendingPathComponent( "example.pdf") as URL
let data = try! Data(contentsOf: pdfURL)
let webView = WKWebView(frame: CGRect(x:20,y:20,width:view.frame.size.width-40, height:view.frame.size.height-40))
webView.load(data, mimeType: "application/pdf", characterEncodingName:"", baseURL: pdfURL.deletingLastPathComponent())
view.addSubview(webView)
The E791BF20-CC53-4FBB-B34A-F73CED74EB5D is application folder in which you have Documents folder containing the pdf file which you want to view.
This will give path of Documents folder.
let fileManager = NSFileManager.defaultManager()
let documentsUrl = fileManager.URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0] as NSURL
print(documentsUrl)
You need to change code
let pdf = documentsUrl + "/<your pdf file name>"
let req = NSURLRequest(URL: pdf)
webView.loadRequest(req)
Hope this works for you.
You are fetching it from bundle not from document directory.
Try this....
var pdf = (NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)).last as? NSURL
pdf = pdf?.URLByAppendingPathComponent( "ST_Business%20Times_07022016.pdf")
let req = NSURLRequest(URL: pdf)
webView.loadRequest(req)
Please check you path has valid file exist or not before loading the file.
let webView : UIWebView!
webView = UIWebView()
webView.frame = self.view.bounds
self.view.addSubview(webView)
let PDF_FILE_PATH = NSBundle.mainBundle().pathForResource("ST_Business%20Times_07022016", ofType: "pdf")
let checkValidation = NSFileManager.defaultManager()
if (checkValidation.fileExistsAtPath(PDF_FILE_PATH!))
{
print("FILE AVAILABLE");
let req = NSURLRequest(URL: NSURL(string: PDF_FILE_PATH!)!)
webView.loadRequest(req)
}
else
{
print("FILE NOT AVAILABLE");
}

Resources