iOS实现PDF文件浏览功能

写了一个小Demo,显示本地PDF格式文件,支持翻页、跳页、缩放。

先看一下效果图:

iOS实现PDF文件浏览功能


iOS开发,显示PDF格式文件方法有很多:

  • 最简单的应该是UIWebView,可以加载本地或网络PDF文件,支持上下滑动浏览、缩放。
  • 优化一点的是用系统的QLPreviewController加载,实现起来也比较方便,支持上下滑动浏览,左后滑动可多PDF文件切换,同时支持原生的分享打印,QLPreviewController支持的文档格式也比较多,如pdf、doc、docx、xls、xlsx、txt、ppt、mp4...
  • 上面两种都没有足够的自定义空间,不在这里做过多的介绍了,另外一种也就是本篇用到的iOS核心图形库:Core Graphics,绘制PDF文档。

简单说一下逻辑,根据本地路径获取到CGPDFDocumentRef,在drawRect中绘制上下文,画出PDF文件。通过UIScrollView实现缩放,添加UIGestureRecognizer实现单击、双击、左滑、右滑功能。基于CATransition实现翻页动画。

下面贴上核心代码:

承载PDF文件视图的控制器:HWPDFBrowseVC

#import <UIKit/UIKit.h>

@interface HWPDFBrowseVC : UIViewController

@property (nonatomic,copy) NSString *filePath;
@property (nonatomic,copy) NSString *fileName;

@end

/*** ---------------分割线--------------- ***/

#import "HWPDFBrowseVC.h"
#import "HWPDFBrowseView.h"
#import "HWPDFBrowseToolBar.h"
#import "HWPDFBrowseScrollView.h"

#define KPicMaxScale 3.0
#define KMainW [UIScreen mainScreen].bounds.size.width
#define KMainH [UIScreen mainScreen].bounds.size.height

@interface HWPDFBrowseVC ()<UIScrollViewDelegate,HWPDFBroeseToolBarDelegate>

@property (nonatomic,weak) HWPDFBrowseScrollView *scrollView;
@property (nonatomic,weak) HWPDFBrowseView *browseView;
@property (nonatomic,weak) HWPDFBrowseToolBar *toolBar;
@property (nonatomic,assign) CGFloat minZoomScale;
@property (nonatomic,assign) CGFloat lastScrContX;

@end

@implementation HWPDFBrowseVC

- (void)viewDidLoad {
 [super viewDidLoad];

 //初始化
 self.view.backgroundColor = [UIColor whiteColor];
 self.navigationItem.title = _fileName;

 //创建控件
 [self creatControl];
}

- (void)viewWillDisappear:(BOOL)animated
{
 [super viewWillDisappear:animated];

 //防止隐藏导航时,左滑返回导航消失
 CGRect temNavBarFrame = self.navigationController.navigationBar.frame;
 temNavBarFrame.origin.y = 20;
 self.navigationController.navigationBar.frame = temNavBarFrame;
}

- (void)creatControl
{
 //导航右侧按钮
 UIButton *deleteBtn = [[UIButton alloc] initWithFrame:CGRectMake(9,40,40)];
 deleteBtn.titleLabel.font = [UIFont systemFontOfSize:16.f];
 [deleteBtn setTitle:@"跳页" forState:UIControlStateNormal];
 [deleteBtn setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
 [deleteBtn addTarget:self action:@selector(navBtnOnClick) forControlEvents:UIControlEventTouchUpInside];
 UIView *rightView = [[UIView alloc] initWithFrame:CGRectMake(0,40)];
 [rightView addSubview:deleteBtn];
 self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightView];

 //scrollView
 HWPDFBrowseScrollView *scrollView = [[HWPDFBrowseScrollView alloc] initWithFrame:[UIScreen mainScreen].bounds];
 scrollView.delegate = self;
 scrollView.backgroundColor = [UIColor blackColor];
 scrollView.maximumZoomScale = KPicMaxScale;
 scrollView.showsVerticalScrollIndicator = NO;
 scrollView.showsHorizontalScrollIndicator = NO;
 [self.view addSubview:scrollView];
 _scrollView = scrollView;

 //pdf视图
 HWPDFBrowseView *browseView = [[HWPDFBrowseView alloc] initWithFilePath:_filePath];
 [scrollView addSubview:browseView];
 _browseView = browseView;

 //绘制pdf视图后缩放至屏幕完全居中显示
 CGRect frame = browseView.frame;
 frame.size.width = browseView.frame.size.width > KMainW ? KMainW : browseView.frame.size.width;
 frame.size.height = frame.size.width * (browseView.frame.size.height / browseView.frame.size.width);
 if (frame.size.height > KMainH) {
 frame.size.height = KMainH;
 frame.size.width = KMainH * (browseView.frame.size.width / browseView.frame.size.height);
 }

 //根据缩放调整
 _minZoomScale = frame.size.width / browseView.frame.size.width;
 scrollView.allowScrollScale = _minZoomScale;
 scrollView.minimumZoomScale = _minZoomScale;
 scrollView.zoomScale = _minZoomScale;

 //底部工具栏
 HWPDFBrowseToolBar *toolBar = [[HWPDFBrowseToolBar alloc] initWithFrame:CGRectMake(0,KMainH - 49,KMainW,49) currentPage:_browseView.currentPage totalPage:_browseView.totalPages];
 toolBar.delegate = self;
 [self.view addSubview:toolBar];
 _toolBar = toolBar;

 //单击
 UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(click)];
 tap.numberOfTouchesRequired = 1;
 tap.numberOfTapsRequired = 1;
 [scrollView addGestureRecognizer:tap];

 //双击
 UITapGestureRecognizer *tapDouble = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(doubleClick)];
 tapDouble.numberOfTapsRequired = 2;
 [scrollView addGestureRecognizer:tapDouble];
 [tap requireGestureRecognizerToFail:tapDouble];

 //右滑手势
 UISwipeGestureRecognizer *rightSwip = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(nextPage)];
 rightSwip.direction = UISwipeGestureRecognizerDirectionLeft;
 [scrollView addGestureRecognizer:rightSwip];

 //左滑手势
 UISwipeGestureRecognizer *leftSwip = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(forwardPage)];
 leftSwip.direction = UISwipeGestureRecognizerDirectionRight;
 [scrollView addGestureRecognizer:leftSwip];
}

- (void)navBtnOnClick
{
 [_toolBar showWindow];
}

//单击屏幕显示隐藏菜单
- (void)click
{
 CGFloat navBarY = _toolBar.frame.origin.y == KMainH - 49 ? -64 : 20;
 CGFloat toolBarY = _toolBar.frame.origin.y == KMainH - 49 ? KMainH : KMainH - 49;

 [UIView animateWithDuration:0.25 animations:^{
 CGRect temNavBarFrame = self.navigationController.navigationBar.frame;
 temNavBarFrame.origin.y = navBarY;
 self.navigationController.navigationBar.frame = temNavBarFrame;
 CGRect temToolBarFrame = _toolBar.frame;
 temToolBarFrame.origin.y = toolBarY;
 _toolBar.frame = temToolBarFrame;
 }];
}

//双击屏幕放大缩小图片
- (void)doubleClick
{
 [UIView animateWithDuration:0.25f animations:^{
 _scrollView.zoomScale = _scrollView.zoomScale == _minZoomScale ? KPicMaxScale : _minZoomScale;
 }];
}

//左滑事件
- (void)nextPage
{
 [_browseView nextPage];
 _toolBar.currentPage = _browseView.currentPage;
}

//右滑事件
- (void)forwardPage
{
 [_browseView prePage];
 _toolBar.currentPage = _browseView.currentPage;
}

#pragma mark - UICouseBrowseToolBarDelegate
- (void)browseToolBar:(HWPDFBrowseToolBar *)browseToolBar didClickFinishButtonWithPage:(NSString *)page
{
 _browseView.currentPage = [page integerValue];
 [_browseView reloadView];
 [_toolBar dismissKeyboard];
 _scrollView.zoomScale = _minZoomScale;
}

- (void)browseToolBar:(HWPDFBrowseToolBar *)browseToolBar didPageButtonWithAction:(BOOL)nextPage
{
 if (nextPage) {
 [self nextPage];
 }else {
 [self forwardPage];
 }
 _scrollView.zoomScale = _minZoomScale;
}

#pragma mark - UIScrollViewDelegate
- (void)scrollViewDidZoom:(UIScrollView *)scrollView
{
 CGFloat offsetX = (scrollView.bounds.size.width > scrollView.contentSize.width) ? (scrollView.bounds.size.width - scrollView.contentSize.width) * 0.5 : 0.0;
 CGFloat offsetY = (scrollView.bounds.size.height > scrollView.contentSize.height) ? (scrollView.bounds.size.height - scrollView.contentSize.height) * 0.5 : 0.0;
 _browseView.center = CGPointMake(scrollView.contentSize.width * 0.5 + offsetX,scrollView.contentSize.height * 0.5 + offsetY - 64);
}

- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
 return _browseView;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
 if (scrollView.isZooming) return;

 //允许翻页的偏移量
 CGFloat movePadding = 70.f;

 //仿苹果原生相册,图片放大后,滑动前在边界时在可以翻页,这里加了±10的偏移量
 if (scrollView.contentOffset.x < - movePadding && _lastScrContX < 10) {
 _scrollView.zoomScale = _minZoomScale;
 [self forwardPage];
 }

 if (scrollView.contentSize.width - scrollView.contentOffset.x < KMainW - movePadding && scrollView.contentSize.width != 0 && fabsf(_lastScrContX + KMainW - scrollView.contentSize.width) < 10) {
 _scrollView.zoomScale = _minZoomScale;
 [self nextPage];
 }
}

//滑动自然停止时调用
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
 _lastScrContX = scrollView.contentOffset.x;
}

//滑动手动停止时调用
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
 _lastScrContX = scrollView.contentOffset.x;
}

- (void)didReceiveMemoryWarning {
 [super didReceiveMemoryWarning];
 // Dispose of any resources that can be recreated.
}

@end

PDF文件视图:HWPDFBrowseView

#import <UIKit/UIKit.h>

@interface HWPDFBrowseView : UIView{
 CGPDFDocumentRef pdfDocumentRef;
}

@property (nonatomic,assign) NSInteger currentPage;
@property (nonatomic,assign) NSInteger totalPages;

- (id)initWithFilePath:(NSString *)filePath;
- (void)reloadView;
- (void)prePage;
- (void)nextPage;

@end

/*** ---------------分割线--------------- ***/

#import "HWPDFBrowseView.h"

@implementation HWPDFBrowseView

- (id)initWithFilePath:(NSString *)filePath
{
 pdfDocumentRef = [self createPDFFromExistFile:filePath];

 self = [super initWithFrame:CGPDFPageGetBoxRect(CGPDFDocumentGetPage(pdfDocumentRef,1),kCGPDFMediaBox)];

 return self;
}

- (CGPDFDocumentRef)createPDFFromExistFile:(NSString *)aFilePath
{
 CFStringRef path = CFStringCreateWithCString(NULL,[aFilePath UTF8String],kCFStringEncodingUTF8);
 CFURLRef urlRef = CFURLCreateWithFileSystemPath(NULL,path,kCFURLPOSIXPathStyle,NO);
 CFRelease(path);
 CGPDFDocumentRef document = CGPDFDocumentCreateWithURL(urlRef);
 CFRelease(urlRef);
 _totalPages = CGPDFDocumentGetNumberOfPages(document);
 _currentPage = 1;
 if (_totalPages == 0) return NULL;

 return document;
}

- (void)reloadView
{
 [self setNeedsDisplay];
}

- (void)drawRect:(CGRect)rect
{
 CGContextRef context = UIGraphicsGetCurrentContext();
 [[UIColor whiteColor] set];
 CGContextFillRect(context,rect);
 CGContextTranslateCTM(context,0.0,rect.size.height);
 CGContextScaleCTM(context,1.0,-1.0);
 CGPDFPageRef page = CGPDFDocumentGetPage(pdfDocumentRef,_currentPage);
 CGAffineTransform pdfTransform = CGPDFPageGetDrawingTransform(page,kCGPDFCropBox,rect,true);
 CGContextConcatCTM(context,pdfTransform);
 CGContextDrawPDFPage(context,page);
}

//上一页
- (void)prePage
{
 if(_currentPage < 2) {
 UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"已经第一页了!" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil ];
 [alert show];
 return;
 }

 --_currentPage;
 [self reloadView];
 [self transitionWithType:@"pageUnCurl" WithSubtype:kCATransitionFromRight ForView:self];
}

//下一页
- (void)nextPage
{
 if(_currentPage >= _totalPages) {
 UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"已经最后一页了!" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil ];
 [alert show];
 return;
 }

 ++_currentPage;
 [self reloadView];
 [self transitionWithType:@"pageCurl" WithSubtype:kCATransitionFromRight ForView:self];
}

//设置翻页动画效果
- (void)transitionWithType:(NSString *)type WithSubtype:(NSString *)subtype ForView:(UIView *)view
{
 CATransition *animation = [CATransition animation];
 animation.duration = 0.7f;
 animation.type = type;
 if (subtype) animation.subtype = subtype;
 animation.timingFunction = UIViewAnimationOptionCurveEaseInOut;
 [view.layer addAnimation:animation forKey:@"animation"];
}

@end

Demo 下载链接

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


当我们远离最新的 iOS 16 更新版本时,我们听到了困扰 Apple 最新软件的错误和性能问题。
欧版/美版 特别说一下,美版选错了 可能会永久丧失4G,不过只有5%的概率会遇到选择运营商界面且部分必须连接到iTunes才可以激活
一般在接外包的时候, 通常第三方需要安装你的app进行测试(这时候你的app肯定是还没传到app store之前)。
前言为了让更多的人永远记住12月13日,各大厂都在这一天将应用变灰了。那么接下来我们看一下Flutter是如何实现的。Flutter中实现整个App变为灰色在Flutter中实现整个App变为灰色是非常简单的,只需要在最外层的控件上包裹ColorFiltered,用法如下:ColorFiltered(颜色过滤器)看名字就知道是增加颜色滤镜效果的,ColorFiltered( colorFilter:ColorFilter.mode(Colors.grey, BlendMode.
flutter升级/版本切换
(1)在C++11标准时,open函数的文件路径可以传char指针也可以传string指针,而在C++98标准,open函数的文件路径只能传char指针;(2)open函数的第二个参数是打开文件的模式,从函数定义可以看出,如果调用open函数时省略mode模式参数,则默认按照可读可写(ios_base:in | ios_base::out)的方式打开;(3)打开文件时的mode的模式是从内存的角度来定义的,比如:in表示可读,就是从文件读数据往内存读写;out表示可写,就是把内存数据写到文件中;
文章目录方法一:分别将图片和文字置灰UIImage转成灰度图UIColor转成灰度颜色方法二:给App整体添加灰色滤镜参考App页面置灰,本质是将彩色图像转换为灰度图像,本文提供两种方法实现,一种是App整体置灰,一种是单个页面置灰,可结合具体的业务场景使用。方法一:分别将图片和文字置灰一般情况下,App页面的颜色深度是24bit,也就是RGB各8bit;如果算上Alpha通道的话就是32bit,RGBA(或者ARGB)各8bit。灰度图像的颜色深度是8bit,这8bit表示的颜色不是彩色,而是256
领导让调研下黑(灰)白化实现方案,自己调研了两天,根据网上资料,做下记录只是学习过程中的记录,还是写作者牛逼
让学前端不再害怕英语单词(二),通过本文,可以对css,js和es6的单词进行了在逻辑上和联想上的记忆,让初学者更快的上手前端代码
用Python送你一颗跳动的爱心
在uni-app项目中实现人脸识别,既使用uni-app中的live-pusher开启摄像头,创建直播推流。通过快照截取和压缩图片,以base64格式发往后端。
商户APP调用微信提供的SDK调用微信支付模块,商户APP会跳转到微信中完成支付,支付完后跳回到商户APP内,最后展示支付结果。CSDN前端领域优质创作者,资深前端开发工程师,专注前端开发,在CSDN总结工作中遇到的问题或者问题解决方法以及对新技术的分享,欢迎咨询交流,共同学习。),验证通过打开选择支付方式弹窗页面,选择微信支付或者支付宝支付;4.可取消支付,放弃支付会返回会员页面,页面提示支付取消;2.判断支付方式,如果是1,则是微信支付方式。1.判断是否在微信内支付,需要在微信外支付。
Mac命令行修改ipa并重新签名打包
首先在 iOS 设备中打开开发者模式。位于:设置 - 隐私&安全 - 开发者模式(需重启)
一 现象导入MBProgressHUD显示信息时,出现如下异常现象Undefined symbols for architecture x86_64: "_OBJC_CLASS_$_MBProgressHUD", referenced from: objc-class-ref in ViewController.old: symbol(s) not found for architecture x86_64clang: error: linker command failed wit
Profiles >> 加号添加 >> Distribution >> "App Store" >> 选择 2.1 创建的App ID >> 选择绑定 2.3 的发布证书(.cer)>> 输入描述文件名称 >> Generate 生成描述文件 >> Download。Certificates >> 加号添加 >> "App Store and Ad Hoc" >> “Choose File...” >> 选择上一步生成的证书请求文件 >> Continue >> Download。
今天有需求,要实现的功能大致如下:在安卓和ios端实现分享功能可以分享链接,图片,文字,视频,文件,等欢迎大佬多多来给萌新指正,欢迎大家来共同探讨。如果各位看官觉得文章有点点帮助,跪求各位给点个“一键三连”,谢啦~声明:本博文章若非特殊注明皆为原创原文链接。