11
votes

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?

4

4 Answers

4
votes

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];
}
2
votes

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.

1
votes

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]];
1
votes

NSData is used to load the pdf files when they are stored locally in any of the directories. To load the pdf which was in your application, use the following code .

NSString *path = [[NSBundle mainBundle] pathForResource:@"FileNameHere" 
                                             ofType:@"pdf"];
NSURL *url = [NSURL fileURLWithPath:path];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[webView loadRequest:request];