美文网首页
iOS开发 PDF的展示,下载,读取本地PDF加载

iOS开发 PDF的展示,下载,读取本地PDF加载

作者: 子小每文 | 来源:发表于2018-02-07 15:00 被阅读0次

一:URL的读取,保存,本地读取保存
1:后台返回的html的话,去加载这些数据,进行展示:

        NSURL *url = [NSURL URLWithString:@"URL"];
        NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
        //[_webView loadHTMLString:_modelArticle.url baseURL:url];
        [_webView loadRequest:request];
        [self addTitleViewWithTitle:_modelArticle.title];

        如果加载的url存在,但是后台需要插入js,去掉广告之类的
        - (void)webViewDidFinishLoad:(UIWebView *)webView {
          //_modelJs.content  是js代码
             [_webView stringByEvaluatingJavaScriptFromString:_modelJs.content];
              }

2:下面是保存PDF到本地:
//判断pdf是否存在,如果不存在进行保存
-(BOOL)TxtisFileExist:(NSString *)fileName {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *path = [paths objectAtIndex:0];
NSString *filePath = [path stringByAppendingPathComponent:fileName];
NSFileManager *fileManager = [NSFileManager defaultManager];
BOOL result = [fileManager fileExistsAtPath:filePath];
NSLog(@"这个文件已经存在:%@",result?@"是的":@"不存在");
return result;
}
3:保存数据
需要UIWebView的扩展类进行存储转NSdata

import "UIWebView+ConverToData.h"

@implementation UIWebView (ConverToData)

  • (NSData *)converToPDF{
    UIViewPrintFormatter *fmt = [self viewPrintFormatter];
    UIPrintPageRenderer *render = [[UIPrintPageRenderer alloc] init];
    [render addPrintFormatter:fmt startingAtPageAtIndex:0];
    CGRect page;
    page.origin.x=0;
    page.origin.y=0;
    page.size.width=600;
    page.size.height=768;

    CGRect printable=CGRectInset( page, 50, 50 );
    [render setValue:[NSValue valueWithCGRect:page] forKey:@"paperRect"];
    [render setValue:[NSValue valueWithCGRect:printable] forKey:@"printableRect"];

    NSMutableData * pdfData = [NSMutableData data];
    UIGraphicsBeginPDFContextToData( pdfData, CGRectZero, nil );

    for (NSInteger i=0; i < [render numberOfPages]; i++)
    {
    UIGraphicsBeginPDFPage();
    CGRect bounds = UIGraphicsGetPDFContextBounds();
    [render drawPageAtIndex:i inRect:bounds];

    }
    UIGraphicsEndPDFContext();
    return pdfData;
    }

//调用上面的方法

//注意了,别用汉语名称去保存,可以用唯一标识进行保存

    NSData *data = [_webView converToPDF];
    NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@"Documents/%@.pdf",[self transform:strName]]];
    BOOL result = [data writeToFile:path atomically:YES];
    if (result) {  @"下载成功"}

4:如果保存下来后直接进行读取本地PDF
如果存在: 调用下面的代码 记住你传过的名字 然后进行UIWeView加载就OK了

  • (void)readPDF:(NSString *)str
    {
    NSString *filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *imageFilePath = [filePath stringByAppendingPathComponent:str];
    NSURL *urlttt = [NSURL fileURLWithPath:imageFilePath];
    NSURLRequest *request = [NSURLRequest requestWithURL:urlttt];
    [_webView loadRequest:request];
    }

二:后台数据是PDF文件如何操作

//这个是下载后台返回的pdf文件进行下载
//首先是判断文件的存没有存在,然后进行数据的下载或者读取

  • (void)download:(NSString *)strurl path:(NSString *)pathName
    {
    if (![self TxtisFileExist:[NSString stringWithFormat:@"%@.pdf",pathName]]) {
    NSString *urlString = strurl;
    NSURL *url = [NSURL URLWithString:[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];

      NSURLSessionDownloadTask *task = [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
          
      } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
          NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
          NSString * documentsDirectory = [paths lastObject];
          NSString * path = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.pdf",[self transform:pathName]]];
          
          return [NSURL fileURLWithPath:path];
      } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
          
          if (error == nil) {
             [self.view showToastMessage:@"下载成功"];
          }else{
              [self.view showToastMessage:@"下载失败,请检查网络或者PDF文件过大"];
              [self addRefreshButton:self.view refreshBlock:^{}];
          }
      }];
      [task resume];
    

    }else{

      NSString *filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
      NSString *imageFilePath = [filePath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.pdf",[self transform:pathName]]];
      NSURL *urlttt = [NSURL fileURLWithPath:imageFilePath];
      NSURLRequest *request = [NSURLRequest requestWithURL:urlttt];
      [_webView loadRequest:request];
    

    }
    }

相关文章

网友评论

      本文标题:iOS开发 PDF的展示,下载,读取本地PDF加载

      本文链接:https://www.haomeiwen.com/subject/ufzozxtx.html