热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

iOS如何实现PDF文件浏览功能

这篇文章主要介绍了iOS如何实现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 @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 ()@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, 0, 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, 0, 40, 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

PDF文件视图:HWPDFBrowseView

#import @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, 0, 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

感谢你能够认真阅读完这篇文章,希望小编分享的“iOS如何实现PDF文件浏览功能”这篇文章对大家有帮助,同时也希望大家多多支持编程笔记,关注编程笔记行业资讯频道,更多相关知识等着你来学习!


推荐阅读
  • 本文介绍了在C#中SByte类型的GetHashCode方法,该方法用于获取当前SByte实例的HashCode。给出了该方法的语法和返回值,并提供了一个示例程序演示了该方法的使用。 ... [详细]
  • 本文介绍了OC学习笔记中的@property和@synthesize,包括属性的定义和合成的使用方法。通过示例代码详细讲解了@property和@synthesize的作用和用法。 ... [详细]
  • C# 7.0 新特性:基于Tuple的“多”返回值方法
    本文介绍了C# 7.0中基于Tuple的“多”返回值方法的使用。通过对C# 6.0及更早版本的做法进行回顾,提出了问题:如何使一个方法可返回多个返回值。然后详细介绍了C# 7.0中使用Tuple的写法,并给出了示例代码。最后,总结了该新特性的优点。 ... [详细]
  • Linux环境变量函数getenv、putenv、setenv和unsetenv详解
    本文详细解释了Linux中的环境变量函数getenv、putenv、setenv和unsetenv的用法和功能。通过使用这些函数,可以获取、设置和删除环境变量的值。同时给出了相应的函数原型、参数说明和返回值。通过示例代码演示了如何使用getenv函数获取环境变量的值,并打印出来。 ... [详细]
  • ScrollView嵌套Collectionview无痕衔接四向滚动,支持自定义TitleView
    本文介绍了如何实现ScrollView嵌套Collectionview无痕衔接四向滚动,并支持自定义TitleView。通过使用MainScrollView作为最底层,headView作为上部分,TitleView作为中间部分,Collectionview作为下面部分,实现了滚动效果。同时还介绍了使用runtime拦截_notifyDidScroll方法来实现滚动代理的方法。具体实现代码可以在github地址中找到。 ... [详细]
  • iOS Swift中如何实现自动登录?
    本文介绍了在iOS Swift中如何实现自动登录的方法,包括使用故事板、SWRevealViewController等技术,以及解决用户注销后重新登录自动跳转到主页的问题。 ... [详细]
  • WPF开发心率检测大数据曲线图的高性能实现方法
    本文介绍了在WPF开发中实现心率检测大数据曲线图的高性能方法。作者尝试过使用Canvas和第三方开源库,但性能和功能都不理想。最终作者选择使用DrawingVisual对象,并结合局部显示的方式实现了自己想要的效果。文章详细介绍了实现思路和具体代码,对于不熟悉DrawingVisual的读者可以去微软官网了解更多细节。 ... [详细]
  • 本文介绍了MVP架构模式及其在国庆技术博客中的应用。MVP架构模式是一种演变自MVC架构的新模式,其中View和Model之间的通信通过Presenter进行。相比MVC架构,MVP架构将交互逻辑放在Presenter内部,而View直接从Model中读取数据而不是通过Controller。本文还探讨了MVP架构在国庆技术博客中的具体应用。 ... [详细]
  • 本文详细介绍了Android中的坐标系以及与View相关的方法。首先介绍了Android坐标系和视图坐标系的概念,并通过图示进行了解释。接着提到了View的大小可以超过手机屏幕,并且只有在手机屏幕内才能看到。最后,作者表示将在后续文章中继续探讨与View相关的内容。 ... [详细]
  • 本文介绍了Cocos2dx学习笔记中的更新函数scheduleUpdate、进度计时器CCProgressTo和滚动视图CCScrollView的用法。详细介绍了scheduleUpdate函数的作用和使用方法,以及schedule函数的区别。同时,还提供了相关的代码示例。 ... [详细]
  • Java太阳系小游戏分析和源码详解
    本文介绍了一个基于Java的太阳系小游戏的分析和源码详解。通过对面向对象的知识的学习和实践,作者实现了太阳系各行星绕太阳转的效果。文章详细介绍了游戏的设计思路和源码结构,包括工具类、常量、图片加载、面板等。通过这个小游戏的制作,读者可以巩固和应用所学的知识,如类的继承、方法的重载与重写、多态和封装等。 ... [详细]
  • 开发笔记:Java是如何读取和写入浏览器Cookies的
    篇首语:本文由编程笔记#小编为大家整理,主要介绍了Java是如何读取和写入浏览器Cookies的相关的知识,希望对你有一定的参考价值。首先我 ... [详细]
  • 在springmvc框架中,前台ajax调用方法,对图片批量下载,如何弹出提示保存位置选框?Controller方法 ... [详细]
  • 本文介绍了在iOS开发中使用UITextField实现字符限制的方法,包括利用代理方法和使用BNTextField-Limit库的实现策略。通过这些方法,开发者可以方便地限制UITextField的字符个数和输入规则。 ... [详细]
  • IOS开发之短信发送与拨打电话的方法详解
    本文详细介绍了在IOS开发中实现短信发送和拨打电话的两种方式,一种是使用系统底层发送,虽然无法自定义短信内容和返回原应用,但是简单方便;另一种是使用第三方框架发送,需要导入MessageUI头文件,并遵守MFMessageComposeViewControllerDelegate协议,可以实现自定义短信内容和返回原应用的功能。 ... [详细]
author-avatar
翔英建辉千慧
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有