Display PDF in UIWebView using loadData

混江龙づ霸主 提交于 2019-12-03 11:42:56

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

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.

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]];
abhilash reddy

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];
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!