iOS中查看&打印 .pdf .doc .docx文件


一、背景需求介绍

怎么让APP支持查看&打印word,pdf文档?
iOS是有支持这个功能的控件QLPreviewController.

配置:

只需导入库:
这里写图片描述

二、示例代码如下:

实现的功能是在一个webView中点击获取下载地址进行下载一个文件,之后用QLPreviewController打开,QLPreviewController支持打印功能.

在.h文件中


#import#import@interface ViewController : UIViewController

//打开word文档需要引入的视图控制器

@property(nonatomic,strong) QLPreviewController *previewController;

@end

在.m文件中

#import "ViewController.h"

#import "AFNetworking.h"

@interface ViewController ()

//保存本地的地址

@property (nonatomic ,copy) NSString *path;

@end

@implementation ViewController

- (void)viewDidLoad {  

  [super viewDidLoad];  

  // Do any additional setup after loading the view, typically from a nib.  

      [self initWeb];  

  }

- (void)initWeb

{

UIWebView *web =[[UIWebView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];

NSString *url = @"网页地址";

NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];

web.delegate = self;

[web loadRequest:request];

[self.view addSubview:web];

}
#pragma UIWebViewDelegate

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType

{

//判断是否是单击

if (navigationType == UIWebViewNavigationTypeLinkClicked)

{

//点击网页中的文件截取到的网址(文件下载地址)

NSURL *url = [request URL];

if([[UIApplication sharedApplication]canOpenURL:url])

{

NSLog(@"url==%@",url);

//缓存到本地沙盒的地址

NSString *savedPath = [NSHomeDirectory() stringByAppendingString:@"/Documents/附件详情"];

[self downloadFileWithOption:nil withInferface:[url absoluteString] savedPath:savedPath downloadSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {

} downloadFailure:^(AFHTTPRequestOperation *operation, NSError *error) {

} progress:^(float progress) {

}];

}

return NO;

}

return YES;

}

//下载文档,并保存(这里比较low还用的AFNetworking 2.x 来下载附件)

- (void)downloadFileWithOption:(NSDictionary *)paramDic withInferface:(NSString*)requestURL savedPath:(NSString*)savedPath downloadSuccess:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success downloadFailure:(void (^)(AFHTTPRequestOperation *operation,NSError *error))failure progress:(void (^)(float progress))progress

{

AFHTTPRequestSerializer *serializer = [AFHTTPRequestSerializer serializer];

NSMutableURLRequest *request =[serializer requestWithMethod:@"GET" URLString:requestURL parameters:paramDic error:nil];

AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc]initWithRequest:request];

[operation setOutputStream:[NSOutputStream outputStreamToFileAtPath:savedPath append:NO]];

[operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {

float p = (float)totalBytesRead / totalBytesExpectedToRead;

progress(p);

//        NSLog(@"download:%f", (float)totalBytesRead / totalBytesExpectedToRead);

}];

[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {

success(operation,responseObject);

_path = nil;

NSDictionary *dic = operation.response.allHeaderFields;

NSLog(@"下载成功,%@",dic);

NSString *fileName = dic[@"Content-Disposition"];

if(fileName){

//判断格式

if ([fileName rangeOfString:@".docx"].location !=NSNotFound) {

//            NSLog(@"docx文档");

NSFileManager *manager = [NSFileManager new];

_path = [savedPath stringByAppendingString:@".docx"];

[manager moveItemAtPath:savedPath toPath:_path error:nil];

}else if ([fileName rangeOfString:@".doc"].location !=NSNotFound){

//            NSLog(@"doc文档");

NSFileManager *manager = [NSFileManager new];

_path = [savedPath stringByAppendingString:@".doc"];

[manager moveItemAtPath:savedPath toPath:_path error:nil];

}else if([fileName rangeOfString:@".png"].location !=NSNotFound){

//            NSLog(@"图片");

_path = [savedPath stringByAppendingString:@".png"];

NSFileManager *manager = [NSFileManager new];

_path = [savedPath stringByAppendingString:@".png"];

[manager moveItemAtPath:savedPath toPath:_path error:nil];

}else if([fileName rangeOfString:@".jpg"].location !=NSNotFound){

//            NSLog(@"图片");

_path = [savedPath stringByAppendingString:@".jpg"];

NSFileManager *manager = [NSFileManager new];

_path = [savedPath stringByAppendingString:@".jpg"];

[manager moveItemAtPath:savedPath toPath:_path error:nil];

}

}

if (_path) {

self.previewController = [QLPreviewController new];

self.previewController.dataSource = self;

[self.previewController setDelegate:self];

//跳转到打开word文档页面

[self presentViewController:self.previewController animated:YES completion:nil];

}

} failure:^(AFHTTPRequestOperation *operation, NSError *error) {

success(operation,error);

NSLog(@"下载失败,error==%@",error);

}];

[operation start];

}

#pragma QLPreViewDelegate



- (NSInteger) numberOfPreviewItemsInPreviewController: (QLPreviewController *) controller{    return 1;}- (id)previewController: (QLPreviewController *)controller previewItemAtIndex:(NSInteger)index

{

return [NSURL fileURLWithPath:_path];

}

- (void)previewControllerDidDismiss:(QLPreviewController *)controller

{

if(![_path  isEqual: @""]){

NSFileManager * fileManager = [[NSFileManager alloc]init];

[fileManager removeItemAtPath:_path error:nil];

}

}

@end

之后的打开的页面如图:

点击print后,连接支持airPrint的打印机进行打印:

Demo下载链接:点击这里

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值