最近项目中要加载一个本地的word/pdf等文件比如《用户隐私政策》《用户注册说明》,有两种方法加载
> 用QLPreviewController控制器实现 步骤 : > 导入库文件 : QuickLook.framework > 导入头文件 : <QuickLook/QuickLook.h> > 创建我们的对象,然后设置dataSource > 用webView来加载word文件
以上两种方法都先把本地word/pdf文件拖入当我们的项目中
有时候会出现path为nil,看看是不是没加进Build Phases-Copy Bundle Resources资源
/*
方法1使用:
1、导入库文件:QuickLook.framework
2、导入头文件:<QuickLook/QuickLook.h>
*/
#import <QuickLook/QuickLook.h> @interface ViewController ()<QLPreviewControllerDataSource,UIWebViewDelegate> @end @implementation ViewController - (void)viewDidLoad {
[super viewDidLoad];
// 方法1:用QLPreviewController控件实现
[self QLPreviewControllerLoad]; // 方法2:用WebView的方法加载word
[self webViewLoad]; } #pragma mark -- QLPreviewController
- (void)QLPreviewControllerLoad {
self.view.backgroundColor = [UIColor lightGrayColor];
QLPreviewController *qlpVC = [[QLPreviewController alloc] init];
qlpVC.dataSource = self;
[self presentViewController:qlpVC animated:YES completion:nil];
} - (NSInteger)numberOfPreviewItemsInPreviewController:(QLPreviewController *)controller {
return ;//需要显示文件的个数
}
- (id<QLPreviewItem>)previewController:(QLPreviewController *)controller previewItemAtIndex:(NSInteger)index {
NSString *path = [[NSBundle mainBundle] pathForResource:@"顺道用户隐私政策.docx" ofType:nil];
NSURL *url = [NSURL fileURLWithPath:path];
return url;
} #pragma mark -- WebView
- (void)webViewLoad {
NSString *path = [[NSBundle mainBundle] pathForResource:@"顺道用户隐私政策" ofType:@"docx"];
NSURL *url = [NSURL fileURLWithPath:path];
UIWebView *webView = [[UIWebView alloc] init];
webView.frame = CGRectMake(, , kScreen_width, kScreen_height);
webView.backgroundColor = [UIColor whiteColor];
[webView loadRequest:[NSURLRequest requestWithURL:url]];
[webView sizeToFit];
webView.scalesPageToFit = YES;
webView.delegate = self;
[self.view addSubview:webView]; } - (void)webViewDidFinishLoad:(UIWebView *)webView {
NSLog(@"webViewDidFinishLoad");
NSString *javascript = [NSString stringWithFormat:@"var script = document.createElement('script');"
"script.type = 'text/javascript';"
"script.text = \"function ResizeImages() { "
"var myimg;"
"var maxwidth=%f;" //缩放系数
"for(i=0;i <document.images.length;i++){"
"myimg = document.images[i];"
"if(myimg.width > maxwidth){"
"var scale = myimg.width/myimg.height;"
"myimg.width = maxwidth;"
"myimg.height = maxwidth/scale;"
"}"
"}"
"}\";"
"document.getElementsByTagName('head')[0].appendChild(script);",CGRectGetWidth(webView.frame)];
[webView stringByEvaluatingJavaScriptFromString:javascript]; //添加调用JS执行的语句
[webView stringByEvaluatingJavaScriptFromString:@"ResizeImages();"];
}