Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display PDF in UIWebView using loadData

I am trying to display a PDF I have stored locally in a UIWebView. This is how I currently attempt to do this:

if (![[NSFileManager defaultManager] fileExistsAtPath:self.url]) {
LOG_ERROR(@"Couldn't load local file. File at path: %@ doesn't exist", self.url);
        return; 
}

nsurl=[NSURL fileURLWithPath:self.url];
NSData *data = [NSData dataWithContentsOfFile:self.url];
LOG_DEBUG(@"data length:%d",[data length]);
[self.webView loadData:data MIMEType:@"application/pdf" textEncodingName:@"utf-8" baseURL:nil];

I have also tried passing nil for textEncoding, as well as using UIWebView's loadRequest. The result is a UIWebView that displays a blank page. No errors occur in the UIWebView delegate method. The strange thing is that data has the correct length, in bytes, for the PDF I am trying to display, which means the file is being found and loaded correctly.

Does anyone have an idea as to what might be going wrong here or how I can better debug this problem?

like image 694
mmontalbo Avatar asked Dec 09 '10 09:12

mmontalbo


3 Answers

Below you can find two different approaches to open a .pdf file on your UIWebView; one from a url and one as NSData:

if (self.pdfDataToLoad) //Loading the pdf as NSData
{ 
    [self.webView loadData:self.pdfData 
                  MIMEType:@"application/pdf" 
          textEncodingName:@"UTF-8" 
                   baseURL:nil];
}
else  //Open the pdf from a URL 
{ 
    NSURL *targetURL = [NSURL URLWithString:@"https://bitcoin.org/bitcoin.pdf"];
    NSURLRequest *request = [NSURLRequest requestWithURL:targetURL];
    [self.webView loadRequest:request];
}
like image 51
Yunus Nedim Mehel Avatar answered Nov 12 '22 23:11

Yunus Nedim Mehel


It turns out the problem was something to do with the file format of the PDFs. I edited them using Illustrator and re-saved them. I guess Mobile Safari doesn't like the way Illustrator formatted the files because each was blank when viewed using the simulator's browser (although I could open the PDFs in regular Safari just fine).

The solution was to open the PDFs using Preview and re-save them. After running each PDF through the Preview save routine I was able to get each PDF to display in a UIWebView without changing any of my code.

like image 2
mmontalbo Avatar answered Nov 13 '22 00:11

mmontalbo


You don't need NSData to load local file, loadRequest should work directly with NSURL

[self.webView loadRequest:[NSURLRequest requestWithURL:nsurl]];

I can only suggest to make NSURL like that

nsurl = [NSURL URLWithString:[self.url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
like image 1
Nikolay Klimchuk Avatar answered Nov 12 '22 22:11

Nikolay Klimchuk