CPDFViewController.m 20 KB

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