使用loadData在UIWebView中显示PDF [英] Display PDF in UIWebView using loadData

查看:87
本文介绍了使用loadData在UIWebView中显示PDF的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试显示我在UIWebView中本地存储的PDF.这是我目前尝试执行的操作:

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

我还尝试过将nil传递给textEncoding,以及使用UIWebView的loadRequest.结果是显示空白页面的UIWebView. UIWebView委托方法中没有发生错误.奇怪的是,对于我要显示的PDF,数据具有正确的长度(以字节为单位),这意味着已正确找到并加载了文件.

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?

推荐答案

在下面,您可以找到两种不同的方法来在UIWebView上打开.pdf文件;一个来自url,另一个来自NSData:

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

这篇关于使用loadData在UIWebView中显示PDF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆