最近公司添加个查看pdf合同的功能,之前随便百度了下发现webView加载或者View自己画都可以显示,不过最后发现少了一样东西,没错红红的签名公章不见了,安卓浏览器打开都没问题,下载文件手机qq打开发现也没有签章,what~~,用掌阅打开也没有,woca,什么鬼,怎么会这样,开始了一段痛苦的纠结中,然后发现qq打开下方分享按钮处有个创建PDF,打开后发现签章出来了,尼玛因此也确定了竟然能出来那么肯定有解决方法,于是开始了爬坑。
开始上代码 1.首先导入系统
QuickLook.fraework
```框架,怎么导入不简述了
2.引入头文件
#import <QuickLook/QuickLook.h>
QLPreviewControllerDataSource
主要一下2个代理方法
-
(NSInteger)numberOfPreviewItemsInPreviewController:(QLPreviewController *)controller{ return 1; }
-
(id)previewController:(QLPreviewController *)controller previewItemAtIndex:(NSInteger)index{
return [NSURL fileURLWithPath:pdfFilePath]; }
完整代码如下:
url 为pdf 地址链接,访问地址返回pdf 数据流
-(void)loadPdfResource:(NSString *)url{ pdfFilePath = [self getFullPath]; NSFileManager *fileManager = [NSFileManager defaultManager];
if(![fileManager fileExistsAtPath:pdfFilePath])
{
// NSLog(@"文件不存在"); // 下载pdf数据 [SVProgressHUD showWithStatus:@"loading..."]; self.pdfData=[[NSMutableData alloc]init]; NSURLSessionConfiguration *config =[NSURLSessionConfiguration defaultSessionConfiguration]; NSURLSession *session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:[NSOperationQueue mainQueue]]; NSURLSessionDataTask *task = [session dataTaskWithURL:[NSURL URLWithString:url]];
[task resume];
}else{
// NSLog(@"文件存在"); [self pushQLPreviewController]; }
}
下载pdf 数据主要 实现了 NSURLSessionDelegate 代理方法
#pragma mark --- 接收到数据调用
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition disposition))completionHandler{ //允许继续响应 completionHandler(NSURLSessionResponseAllow); //获取文件的总大小 // NSInteger totalLength = response.expectedContentLength; }
#pragma mark --- 接收到数据调用
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData )data{ NSPrintf(@"didReceiveData:%@",data); //将每次接受到的数据拼接起来 [self.pdfData appendData:data]; //计算当前下载的长度 // NSInteger nowlength = self.pdfData .length; // CGFloat value = nowlength1.0/self.totalLength; }
#pragma mark ---下载完成调用
-
(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(nullable NSError *)error{ NSLog(@"self.pdfData:\n%@",self.pdfData);
NSString *filename =[self getFullPath]; [self.pdfData writeToFile:filename atomically:YES]; [SVProgressHUD dismiss];
if (self.pdfData) { NSLog(@"OK"); [self showPDFWebView: filename]; }else{ NSLog(@"Sorry"); }
}
下载完成 写入本地数据 之后 展示pdf,重点来了!
-(void)showPDFWebView:(NSString *)filename{
NSFileManager *fileManager = [NSFileManager defaultManager];
if(![fileManager fileExistsAtPath:pdfFilePath])
{
NSLog(@"文件不存在");
}else{
NSLog(@"文件存在");
[self pushQLPreviewController];
}
}
推出pdf 页面
-(void)pushQLPreviewController{ QLPreviewController *QLPVC = [[QLPreviewController alloc] init]; QLPVC.dataSource = self; [self.navigationController pushViewController:QLPVC animated:YES]; }
最后需要自定义 self.pdfData
over~