CPDFViewController.m 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477
  1. //
  2. // CPDFViewController.m
  3. // viewer-ctrl-demo
  4. //
  5. // Copyright © 2014-2023 PDF Technologies, Inc. All Rights Reserved.
  6. //
  7. // THIS SOURCE CODE AND ANY ACCOMPANYING DOCUMENTATION ARE PROTECTED BY INTERNATIONAL COPYRIGHT LAW
  8. // AND MAY NOT BE RESOLD OR REDISTRIBUTED. USAGE IS BOUND TO THE ComPDFKit LICENSE AGREEMENT.
  9. // UNAUTHORIZED REPRODUCTION OR DISTRIBUTION IS SUBJECT TO CIVIL AND CRIMINAL PENALTIES.
  10. // This notice may not be removed from this file.
  11. //
  12. #import "CPDFViewController.h"
  13. #import <ComPDFKit/ComPDFKit.h>
  14. #import <compdfkit_tools/compdfkit_tools.h>
  15. @interface CPDFViewController ()<UISearchBarDelegate,CPDFViewDelegate,CPDFListViewDelegate, CPDFMoreListViewDelegate, CSearchToolbarDelegate, CPDFDisplayViewDelegate, CPDFBOTAViewControllerDelegate,CPDFSearchResultsDelegate, CPDFThumbnailViewControllerDelegate,CPDFPopMenuViewDelegate,UIDocumentPickerDelegate,CPDFPopMenuDelegate>
  16. @property(nonatomic, strong) NSString *filePath;
  17. @property(nonatomic, strong) CPDFListView *pdfListView;
  18. @property(nonatomic, strong) CNavigationRightView *rightView;
  19. @property(nonatomic, strong) CSearchToolbar *searchToolbar;
  20. @property(nonatomic, strong) CActivityIndicatorView *loadingView;
  21. @property(nonatomic, strong) NSString *navigationTitle;
  22. @property(nonatomic, strong) CNavigationBarTitleButton * titleButton;
  23. @property(nonatomic, strong) CPDFPopMenu *popMenu;
  24. @property(nonatomic, assign) BOOL popMenuClosed;
  25. @end
  26. @implementation CPDFViewController
  27. #pragma mark - Initializers
  28. - (instancetype)initWithFilePath:(NSString *)filePath {
  29. if(self = [super init]) {
  30. self.filePath = filePath;
  31. }
  32. return self;
  33. }
  34. - (void)viewDidLoad {
  35. [super viewDidLoad];
  36. self.view.backgroundColor = [CPDFColorUtils CPDFViewControllerBackgroundColor];
  37. self.pdfListView = [[CPDFListView alloc] initWithFrame:self.view.bounds];
  38. self.pdfListView.performDelegate = self;
  39. self.pdfListView.delegate = self;
  40. self.pdfListView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
  41. [self.view addSubview:self.pdfListView];
  42. UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"CPDFThunbnailImageEnter" inBundle:[NSBundle bundleForClass:self.class] compatibleWithTraitCollection:nil] style:UIBarButtonItemStylePlain target:self action:@selector(buttonItemClicked_thumbnail:)];
  43. self.navigationItem.leftBarButtonItem = leftItem;
  44. __block typeof(self) blockSelf = self;
  45. self.rightView = [[CNavigationRightView alloc] initWithDefaultItemsClickBack:^(NSUInteger tag) {
  46. switch (tag) {
  47. case CNavigationRightTypeSearch:
  48. [blockSelf navigationRightItemSearch];
  49. break;
  50. case CNavigationRightTypeBota:
  51. [blockSelf navigationRightItemBota];
  52. break;
  53. default:
  54. case CNavigationRightTypeMore:
  55. [blockSelf navigationRightItemMore];
  56. break;
  57. }
  58. }];
  59. self.searchToolbar = [[CSearchToolbar alloc] initWithPDFView:self.pdfListView];
  60. self.searchToolbar.delegate = self;
  61. [self reloadDocumentWithFilePath:self.filePath completion:^(BOOL result) {
  62. }];
  63. }
  64. - (void)viewWillLayoutSubviews {
  65. [super viewWillLayoutSubviews];
  66. if(!self.popMenuClosed) {
  67. if (@available(iOS 11.0, *)) {
  68. [self.popMenu showMenuInRect:CGRectMake(self.view.frame.size.width - self.view.safeAreaInsets.right - 250, CGRectGetMaxY(self.navigationController.navigationBar.frame), 250, 200)];
  69. } else {
  70. // Fallback on earlier versions
  71. [self.popMenu showMenuInRect:CGRectMake(self.view.frame.size.width - 250, CGRectGetMaxY(self.navigationController.navigationBar.frame), 250, 200)];
  72. }
  73. }
  74. CGFloat tPosY = 0;
  75. CGFloat bottomY = 0;
  76. CGFloat height = 0;
  77. if (@available(iOS 11.0, *))
  78. height += self.view.safeAreaInsets.bottom;
  79. if (!self.navigationController.navigationBarHidden) {
  80. CGRect rectStatus = [[UIApplication sharedApplication] statusBarFrame];
  81. tPosY = self.navigationController.navigationBar.frame.size.height + rectStatus.size.height;
  82. } else {
  83. bottomY = 0;
  84. }
  85. if (@available(iOS 11.0, *)) {
  86. self.pdfListView.frame = CGRectMake(self.view.safeAreaInsets.left, tPosY, self.view.frame.size.width - self.view.safeAreaInsets.left - self.view.safeAreaInsets.right, self.view.frame.size.height - tPosY- bottomY);
  87. } else {
  88. self.pdfListView.frame = CGRectMake(0, tPosY, self.view.frame.size.width, self.view.frame.size.height - tPosY-bottomY);
  89. }
  90. }
  91. #pragma mark - Accessors
  92. #pragma mark - Public method
  93. - (void)reloadDocumentWithFilePath:(NSString *)filePath completion:(void (^)(BOOL result))completion {
  94. self.title = [[filePath lastPathComponent] stringByDeletingPathExtension];
  95. _navigationTitle = self.title;
  96. //
  97. [self.titleButton setTitle:self.title forState:UIControlStateNormal];
  98. [self.navigationController.view setUserInteractionEnabled:NO];
  99. if (![self.loadingView superview]) {
  100. [self.view addSubview:self.loadingView];
  101. }
  102. [self.loadingView startAnimating];
  103. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  104. NSURL *url = [NSURL fileURLWithPath:filePath];
  105. CPDFDocument *document = [[CPDFDocument alloc] initWithURL:url];
  106. dispatch_async(dispatch_get_main_queue(), ^{
  107. [self.navigationController.view setUserInteractionEnabled:YES];
  108. [self.loadingView stopAnimating];
  109. [self.loadingView removeFromSuperview];
  110. if (document.error && document.error.code != CPDFDocumentPasswordError) {
  111. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"OK", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
  112. [self.navigationController popViewControllerAnimated:YES];
  113. }];
  114. UIAlertController *alert = [UIAlertController alertControllerWithTitle:@""
  115. message:NSLocalizedString(@"Sorry PDF Reader Can't open this pdf file!", nil)
  116. preferredStyle:UIAlertControllerStyleAlert];
  117. [alert addAction:okAction];
  118. if (completion) {
  119. completion(NO);
  120. }
  121. } else {
  122. self.pdfListView.document = document;
  123. if (completion) {
  124. completion(YES);
  125. }
  126. }
  127. });
  128. });
  129. }
  130. #pragma mark - Action
  131. - (void)navigationRightItemSearch {
  132. [self.searchToolbar showInView:self.navigationController.navigationBar];
  133. self.title = nil;
  134. self.navigationItem.rightBarButtonItem = nil;
  135. self.navigationItem.leftBarButtonItem = nil;
  136. }
  137. - (void)navigationRightItemBota {
  138. CPDFBOTAViewController *botaViewController = [[CPDFBOTAViewController alloc] initWithPDFView:self.pdfListView];
  139. botaViewController.delegate = self;
  140. AAPLCustomPresentationController *presentationController NS_VALID_UNTIL_END_OF_SCOPE;
  141. presentationController = [[AAPLCustomPresentationController alloc] initWithPresentedViewController:botaViewController presentingViewController:self];
  142. botaViewController.transitioningDelegate = presentationController;
  143. [self presentViewController:botaViewController animated:YES completion:nil];
  144. }
  145. - (void)navigationRightItemMore {
  146. CPDFPopMenuView * menuView = [[CPDFPopMenuView alloc] initWithFrame:CGRectMake(0, 0, 200, 200)];
  147. menuView.delegate = self;
  148. self.popMenu = [CPDFPopMenu popMenuWithContentView:menuView];
  149. self.popMenu.dimCoverLayer = YES;
  150. self.popMenu.delegate = self;
  151. if (@available(iOS 11.0, *)) {
  152. [self.popMenu showMenuInRect:CGRectMake(self.view.frame.size.width - self.view.safeAreaInsets.right - 250, CGRectGetMaxY(self.navigationController.navigationBar.frame), 250, 200)];
  153. } else {
  154. // Fallback on earlier versions
  155. [self.popMenu showMenuInRect:CGRectMake(self.view.frame.size.width - 250, CGRectGetMaxY(self.navigationController.navigationBar.frame), 250, 200)];
  156. }
  157. }
  158. - (void)buttonItemClicked_thumbnail:(id)sender {
  159. CPDFThumbnailViewController *thumbnailViewController = [[CPDFThumbnailViewController alloc] initWithPDFView:self.pdfListView];
  160. thumbnailViewController.delegate = self;
  161. AAPLCustomPresentationController *presentationController NS_VALID_UNTIL_END_OF_SCOPE;
  162. presentationController = [[AAPLCustomPresentationController alloc] initWithPresentedViewController:thumbnailViewController presentingViewController:self];
  163. thumbnailViewController.transitioningDelegate = presentationController;
  164. [self presentViewController:thumbnailViewController animated:YES completion:nil];
  165. }
  166. - (void)menuItemClick_CopyAction:(id)sender {
  167. if (self.pdfListView.currentSelection.string)
  168. [[UIPasteboard generalPasteboard] setString:self.pdfListView.currentSelection.string];
  169. [self.pdfListView clearSelection];
  170. }
  171. #pragma mark - CPDFViewDelegate
  172. - (void)PDFViewDocumentDidLoaded:(CPDFView *)pdfView {
  173. UIBarButtonItem* rightItem = [[UIBarButtonItem alloc] initWithCustomView:self.rightView];
  174. self.navigationItem.rightBarButtonItem = rightItem;
  175. }
  176. - (void)PDFViewCurrentPageDidChanged:(CPDFView *)pdfView {
  177. NSLog(@"");
  178. }
  179. #pragma mark - CPDFListViewDelegate
  180. - (void)PDFListViewPerformTouchEnded:(CPDFListView *)pdfView {
  181. CGFloat tPosY = 0;
  182. if (self.navigationController.navigationBarHidden) {
  183. [self.navigationController setNavigationBarHidden:NO animated:YES];
  184. [UIView animateWithDuration:0.3 animations:^{
  185. self.pdfListView.pageSliderView.alpha = 1.0;
  186. }];
  187. CGRect rectStatus = [[UIApplication sharedApplication] statusBarFrame];
  188. tPosY = self.navigationController.navigationBar.frame.size.height + rectStatus.size.height;
  189. } else {
  190. [self.navigationController setNavigationBarHidden:YES animated:YES];
  191. [UIView animateWithDuration:0.3 animations:^{
  192. self.pdfListView.pageSliderView.alpha = 0.0;
  193. }];
  194. }
  195. if (@available(iOS 11.0, *)) {
  196. self.pdfListView.frame = CGRectMake(self.view.safeAreaInsets.left, tPosY, self.view.frame.size.width - self.view.safeAreaInsets.left - self.view.safeAreaInsets.right, self.view.frame.size.height - self.view.safeAreaInsets.bottom- tPosY);
  197. } else {
  198. self.pdfListView.frame = CGRectMake(0, tPosY, self.view.frame.size.width, self.view.frame.size.height - tPosY);
  199. }
  200. }
  201. #pragma mark - CSearchToolbarDelegate
  202. - (void)searchToolbar:(CSearchToolbar *)searchToolbar onSearchQueryResults:(NSArray *)results {
  203. if ([results count] < 1) {
  204. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"OK", nil)
  205. style:UIAlertActionStyleCancel
  206. handler:nil];
  207. UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil
  208. message:NSLocalizedString(@"your have‘t search result", nil)
  209. preferredStyle:UIAlertControllerStyleAlert];
  210. [alert addAction:cancelAction];
  211. [self presentViewController:alert animated:YES completion:nil];
  212. return;
  213. }
  214. CPDFSearchResultsViewController* searchResultController = [[CPDFSearchResultsViewController alloc] initWithResultArray:results keyword:searchToolbar.searchKeyString document:self.pdfListView.document];
  215. searchResultController.delegate = self;
  216. AAPLCustomPresentationController *presentationController NS_VALID_UNTIL_END_OF_SCOPE;
  217. presentationController = [[AAPLCustomPresentationController alloc] initWithPresentedViewController:searchResultController presentingViewController:self];
  218. searchResultController.transitioningDelegate = presentationController;
  219. [self presentViewController:searchResultController animated:YES completion:nil];
  220. }
  221. - (void)searchToolbarOnExitSearch:(CSearchToolbar *)searchToolbar {
  222. if([searchToolbar superview]) {
  223. [searchToolbar removeFromSuperview];
  224. UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:self.rightView];
  225. self.navigationItem.rightBarButtonItem = rightItem;
  226. self.title = self.navigationTitle;
  227. UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"CPDFThunbnailImageEnter" inBundle:[NSBundle bundleForClass:self.class] compatibleWithTraitCollection:nil] style:UIBarButtonItemStylePlain target:self action:@selector(buttonItemClicked_thumbnail:)];
  228. self.navigationItem.leftBarButtonItem = leftItem;
  229. }
  230. }
  231. #pragma mark - CPDFDisplayViewDelegate
  232. - (void)displayViewControllerDismiss:(CPDFDisplayViewController *)displayViewController {
  233. [self.navigationController popToRootViewControllerAnimated:YES];
  234. }
  235. #pragma mark - CPDFBOTAViewControllerDelegate
  236. - (void)botaViewControllerDismiss:(CPDFBOTAViewController *)botaViewController {
  237. [self.navigationController dismissViewControllerAnimated:YES completion:nil];
  238. }
  239. #pragma mark - CPDFSearchResultsDelegate
  240. - (void)searchResultsView:(CPDFSearchResultsViewController *)resultVC forSelection:(CPDFSelection *)selection indexPath:(NSIndexPath *)indexPath {
  241. [self.navigationController popViewControllerAnimated:YES];
  242. NSInteger pageIndex = [self.pdfListView.document indexForPage:selection.page];
  243. [self.pdfListView goToPageIndex:pageIndex animated:NO];
  244. [self.pdfListView setHighlightedSelection:selection animated:YES];
  245. }
  246. -(void)searchResultsViewControllerDismiss:(CPDFSearchResultsViewController *)searchResultsViewController {
  247. [self.navigationController popViewControllerAnimated:YES];
  248. }
  249. #pragma mark - CPDFPopMenuDelegate
  250. - (void)MenuDidClosedIn:(CPDFPopMenu *)menu isClosed:(BOOL)isClosed {
  251. self.popMenuClosed = isClosed;
  252. }
  253. #pragma mark - CPDFThumbnailViewControllerDelegate
  254. - (void)thumbnailViewController:(CPDFThumbnailViewController *)thumbnailViewController pageIndex:(NSInteger)pageIndex {
  255. [self.pdfListView goToPageIndex:pageIndex animated:NO];
  256. [self.navigationController popViewControllerAnimated:YES];
  257. }
  258. #pragma mark - CPDFMenuViewdelegate
  259. - (void)menuDidClickAtView:(CPDFPopMenuView *)view clickType:(CPDFPopMenuViewType)viewType {
  260. switch (viewType) {
  261. case CPDFPopMenuViewTypeSetting:
  262. //display controller
  263. {
  264. [self.popMenu hideMenu];
  265. CPDFDisplayViewController *displayVc = [[CPDFDisplayViewController alloc] initWithPDFView:self.pdfListView];
  266. displayVc.delegate = self;
  267. AAPLCustomPresentationController *presentationController NS_VALID_UNTIL_END_OF_SCOPE;
  268. presentationController = [[AAPLCustomPresentationController alloc] initWithPresentedViewController:displayVc presentingViewController:self];
  269. displayVc.transitioningDelegate = presentationController;
  270. [self presentViewController:displayVc animated:YES completion:nil];
  271. }
  272. break;
  273. case CPDFPopMenuViewTypeInfo:
  274. {
  275. [self.popMenu hideMenu];
  276. CPDFInfoViewController * infoVc = [[CPDFInfoViewController alloc] initWithPDFView:self.pdfListView];
  277. AAPLCustomPresentationController *presentationController NS_VALID_UNTIL_END_OF_SCOPE;
  278. presentationController = [[AAPLCustomPresentationController alloc] initWithPresentedViewController:infoVc presentingViewController:self];
  279. infoVc.transitioningDelegate = presentationController;
  280. [self presentViewController:infoVc animated:YES completion:nil];
  281. }
  282. break;
  283. case CPDFPopMenuViewTypeShare:
  284. {
  285. [self.popMenu hideMenu];
  286. if (self.pdfListView.isEdited) {
  287. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  288. [self.pdfListView commitEditing];
  289. dispatch_async(dispatch_get_main_queue(), ^{
  290. [self.pdfListView endOfEditing];
  291. [self shareAction];
  292. });
  293. });
  294. } else {
  295. [self.pdfListView endOfEditing];
  296. [self shareAction];
  297. }
  298. }
  299. break;
  300. case CPDFPopMenuViewTypeAddFile:
  301. {
  302. [self.popMenu hideMenu];
  303. NSArray *documentTypes = @[@"com.adobe.pdf"];
  304. UIDocumentPickerViewController *documentPickerViewController = [[UIDocumentPickerViewController alloc] initWithDocumentTypes:documentTypes inMode:UIDocumentPickerModeOpen];
  305. documentPickerViewController.delegate = self;
  306. [self presentViewController:documentPickerViewController animated:YES completion:nil];
  307. }
  308. default:
  309. break;
  310. }
  311. }
  312. - (void)shareAction {
  313. UIActivityViewController *activityVC = [[UIActivityViewController alloc]initWithActivityItems:@[self.pdfListView.document.documentURL] applicationActivities:nil];
  314. activityVC.definesPresentationContext = YES;
  315. [self presentViewController:activityVC animated:YES completion:nil];
  316. activityVC.completionWithItemsHandler = ^(UIActivityType _Nullable activityType, BOOL completed, NSArray * _Nullable returnedItems, NSError * _Nullable activityError) {
  317. if (completed) {
  318. NSLog(@"Success!");
  319. } else {
  320. NSLog(@"Failed Or Canceled!");
  321. }
  322. };
  323. }
  324. #pragma mark - UIDocument Picker
  325. - (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentsAtURLs:(NSArray<NSURL *> *)urls{
  326. __weak typeof(self) weakSelf = self;
  327. //获取授权
  328. BOOL fileUrlAuthozied = [urls.firstObject startAccessingSecurityScopedResource];
  329. if(fileUrlAuthozied){
  330. //通过文件协调工具来得到新的文件地址,以此得到文件保护功能
  331. NSFileCoordinator *fileCoordinator = [[NSFileCoordinator alloc] init];
  332. NSError *error;
  333. //读取文件
  334. [fileCoordinator coordinateReadingItemAtURL:urls.firstObject options:0 error:&error byAccessor:^(NSURL *newURL) {
  335. NSFileManager * fileManager = [NSFileManager defaultManager];
  336. NSString * appDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
  337. NSString *fileName = [newURL lastPathComponent];
  338. NSString * filePath = [appDir stringByAppendingPathComponent:fileName];
  339. if(![fileManager fileExistsAtPath:filePath]) {
  340. BOOL filePresent = [weakSelf copyMissingFile:newURL.path toPath:appDir];
  341. NSString * savedPath = [NSString stringWithFormat:@"%@/%@",appDir,fileName];
  342. [weakSelf reloadDocumentWithFilePath:savedPath completion:^(BOOL result) {
  343. [weakSelf.pdfListView reloadInputViews];
  344. }];
  345. }
  346. NSError *error = nil;
  347. if (error) {
  348. //
  349. } else {
  350. }
  351. [self dismissViewControllerAnimated:YES completion:NULL];
  352. }];
  353. [urls.firstObject stopAccessingSecurityScopedResource];
  354. }else{
  355. //Error handling
  356. NSLog(@"Faild");
  357. }
  358. }
  359. - (BOOL)copyMissingFile:(NSString*)sourcePath toPath:(NSString*)toPath {
  360. BOOL retVal = YES;
  361. NSString * finalLocation = [toPath stringByAppendingPathComponent:[sourcePath lastPathComponent]];
  362. if(![[NSFileManager defaultManager] fileExistsAtPath:finalLocation]) {
  363. retVal = [[NSFileManager defaultManager] copyItemAtPath:sourcePath toPath:finalLocation error:NULL];
  364. }
  365. return retVal;
  366. }
  367. @end