I'm trying to display a pdf on iOS devices using the UIDocumentInteractionController presentPreviewAnimated method, but it keeps displaying a blank document. I think it might have to do with the character encoding, but I'm not sure. If I use a UIWebView, I can get the pdf to display, just not with the document interaction controller.
// UPDATE 9/18/14
This is now working with the GM release of Xcode 6.
// UPDATE 8/22/14
Oddly enough, from the DocumentInteractionController, if I tap on the "Open In" icon in the top right corner and choose something like iBooks, the pdf displays correctly. It seems as though it's just the preview that doesn't want to display it on the screen.
Here's my code (in Swift):
// data is coming in as NSISOLatin1StringEncoding
func displayPdfInUIDocumentInteractionController(data: NSData) {
let fileName = NSTemporaryDirectory().stringByAppendingPathComponent("myFile.pdf")
let url: NSURL! = NSURL(fileURLWithPath: fileName)
// this does not seem to make a difference
// let pdfString = NSString(data: data, encoding: NSISOLatin1StringEncoding)
// pdfString.writeToURL(url!, atomically: true, encoding: NSISOLatin1StringEncoding, error: nil)
data.writeToURL(url, atomically: true)
if url != nil {
let docController = UIDocumentInteractionController(URL: url)
docController.UTI = "com.adobe.pdf"
docController.delegate = self
docController.presentPreviewAnimated(true)
}
}
This code does display the pdf correctly:
// data is coming in as NSISOLatin1StringEncoding
func displayPdfInUIWebView(data: NSData) {
let rect = UIScreen.mainScreen().bounds
let screenSize = rect.size
let webView = UIWebView(frame: CGRectMake(0,0,screenSize.width,screenSize.height))
webView.autoresizesSubviews = true
webView.autoresizingMask = (UIViewAutoresizing.FlexibleHeight | UIViewAutoresizing.FlexibleWidth)
webView.loadData(data, MIMETYype: "application/pdf", textEncodingName: "ISO-8859-1", baseUrl: nil)
self.view.addSubview(webView)
}
Is there any reason the first function should not be working? It doesn't error out, just displays a blank page.
I'm not using Swift, but I had basically the same problem with straight up Objective-C. Before iOS8, my UIDocumentInteractionController displayed pretty much every file type i threw at it including PDF. But in iOS8, the PDF files would no longer display for me.
I WAS creating it this way:
[[[UIDocumentInteractionController alloc] init] autorelease]
I changed the call to create it like this:
[UIDocumentInteractionController interactionControllerWithURL:myUrl]
And now my PDF files display again (and the others appear to be ok too still).
This is working with the GM release of Xcode. Guess it was just a bug.
Related
I'm showing a pdf file inside a UIDocumentInteractionController, like this:
let docController = UIDocumentInteractionController(url: documentsURL)
let url = NSURL(string:"itms-books:");
if UIApplication.shared.canOpenURL(url! as URL) {
docController.delegate = self
docController.presentPreview(animated: true)
}
I need to automatically scroll to the last page when the controller is shown, is there a way to do that? I didn't find one. Thanks to anyone who will send help!
I am afraid there is not a straight forward solution for this, even the documentation says it's a UIViewController but Xcode shows it is inherited from NSObject.
I'd recommend either rendering the PDF on a WKWebView or a UIScrollView. This will give you a room to wiggle.
I have saved and opened a PDF file on my view controller, and then I save the array of PDFs to the system data. I then pull my array from the data and use the string of the location in the new view controller. However when I attempt to load the file at said directory it fails to appear in the WebView, even though I was able to load it from the same directory on the first ViewController.
How can I get it to open after the app has been closed?
Here is how I save and open the PDF the first time:
func generatePreview() {
let A4paperSize = CGSize(width: 595, height: 842)
let pdf = SimplePDF(pageSize: A4paperSize, pageMargin: 20.0)
createFirstPage(x: pdf)
pdf.beginNewPage()
addAreas(x: pdf)
//add disclamer and like dress the pdf up
let pdfData = pdf.generatePDFdata()
let resourceDocPath = (FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)).last! as URL
let pdfNameFromUrl = "Survey-\(finalOverview.name).pdf"
let actualPath = resourceDocPath.appendingPathComponent(pdfNameFromUrl)
do {
try pdfData.write(to: actualPath, options: .atomic)
print("pdf successfully saved!")
} catch {
print("Pdf could not be saved")
}
let request = URLRequest(url: actualPath)
pdfPreview.load(request)
let pdfObj = pdfArray(fileTitle: finalOverview.name, fileName: actualPath)
//pdfView.GlobalVariable.myPDFs.append(pdfObj)
savePDF(x: pdfObj)
}
I made the mentioned changes but still no luck
My issue was when I was creating the string the second time, the optional was not wrapped. So when I unwrapped it the code worked as intended.
A Mac app requires that a HTML file be called in a WebView (the legacy type, not the newer WKWebView) in a localized form to present the user with some content.
As I side note, I realize that WebView should not be used today, and WKWebView is preferred, however this is a legacy app that currently needs support.
I've used a similar method for the iOS version, however it does not seem to be working. The HTML files are simply called "Term.HTML" and are placed in each localization folder alongside the localized string and all other localized content. This is the code I tried to use:
NSString *htmlFile = [[NSBundle mainBundle] pathForResource:NSLocalizedString(#"fileTerm", nil) ofType:#"html"];
htmlString = [NSString stringWithContentsOfFile:htmlFile encoding:NSUTF8StringEncoding error:nil];
[termsView takeStringURLFrom:htmlString];
Where my localized strings file each contain a line that says:
"fileTerm" = "Term";
This is what links the declaration of the first line to the actual file. It works in iOS. However, when running the app and the view containing the WebView attempt to the run, XCode will automatically create a breakpoint on the third line when I actually attempt to give the HTML file to "termsView" which is my WebView. After skipping this breakpoint, and forcing the app to run, the whole view containing the WebView will simply not appear. I would be thankful if anyone knew why this was or if there was a better way to do this? Thank you everyone!
may be someone needs in SWift: I solved this problem with saving 3 html file for every language, and then in ViewController class checked current app language. And called up the html file for current language
func loadHtmlFile() {
let preferredLanguage = NSLocale.preferredLanguages[0]
if preferredLanguage == "kz" {
let url = Bundle.main.url(forResource: "aboutUs_kz", withExtension:"html")
let request = URLRequest(url: url!)
webView.load(request)
}
if preferredLanguage == "ru" {
let url = Bundle.main.url(forResource: "aboutUs_ru", withExtension:"html")
let request = URLRequest(url: url!)
webView.load(request)
}
if preferredLanguage == "en" {
let url = Bundle.main.url(forResource: "aboutUs_en", withExtension:"html")
let request = URLRequest(url: url!)
webView.load(request)
}
}
in viewDidLoad()
override func viewDidLoad() {
super.viewDidLoad()
loadHtmlFile()
}
I am new to iOS development. In my project i am displaying a exerciseFilePath on tableview.
the response is given below.
"exerciseId" : 1,
"exerciseName" : "Fitness Exercise",
"exerciseFilePath" : "\/p\/pdf\/exercise_pdf\/fitness_exercise.pdf"
i need to display the pdf in another view on didSelectRowAtIndexpath.
i Dont know how to display the pdf and what are steps to be followed to display that pdf.
I hope you understand my problem. please help me how I can do this.
Why don't you use QLPreviewController or UIDocumentInteractionController?
Now in your case you can do it by using webView:
let req = NSURLRequest(url: pdf) //pdf is your pdf path
let webView = UIWebView(frame: CGRect(x:0,y:0,width:self.view.frame.size.width,height: self.view.frame.size.height-40)) //Adjust view area here
webView.loadRequest(req as URLRequest)
self.view.addSubview(webView)
Some tutorials:
QLPreviewController example
UIDocumentInteractionController example
I am opening a word document file in UIWebView.
It works perfect but the problem is that when I open that doc file it does not display in proper format like in word.
In UIWebView :
Code :
let url = NSURL(string: self.docUrl.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!)
let request = NSURLRequest(URL: url!)
webView.loadRequest(request)
webView.delegate = self
webView.scalesPageToFit = true // I have also try by removing this statement
webView.autoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight
Given that you have scales pages to fit, it looks like you might not have constraints setup correctly.
You will need to create constraints between your UIWebView and its parent to ensure that the webView takes over the whole screen.
You can create constraints both in storyboard as well as in code.