CPDFViewBaseController.swift 52 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181
  1. //
  2. // CPDFViewBaseController.swift
  3. // ComPDFKit_Tools
  4. //
  5. // Copyright © 2014-2024 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 UIKit
  13. import ComPDFKit
  14. public let SAMPLESFOLDER = NSHomeDirectory().appending("/Documents/Samples")
  15. public let VIEWERSFOLDER = NSHomeDirectory().appending("/Documents/Viewer")
  16. public let ANNOTATIONSFOLDER = NSHomeDirectory().appending("/Documents/Annotations")
  17. public let FORMSFOLDER = NSHomeDirectory().appending("/Documents/Forms")
  18. public let SIGNATURESFOLDER = NSHomeDirectory().appending("/Documents/Signatures")
  19. public let CONTENTEDITORFOLDER = NSHomeDirectory().appending("/Documents/ContentEditor")
  20. public let SECURITYFOLDER = NSHomeDirectory().appending("/Documents/Security")
  21. public let DOCUMENTEDITORFOLDER = NSHomeDirectory().appending("/Documents/DocumentEditor")
  22. public let WATERMARKFOLDER = NSHomeDirectory().appending("/Documents/Watermark")
  23. public let TEMPOARTFOLDER = NSTemporaryDirectory().appending("Samples")
  24. @objc public protocol CPDFViewBaseControllerDelete: AnyObject {
  25. @objc optional func PDFViewBaseControllerDissmiss(_ baseControllerDelete: CPDFViewBaseController)
  26. }
  27. open class CPDFViewBaseController: UIViewController, CPDFListViewDelegate, CPDFViewDelegate, CSearchToolbarDelegate, CPDFBOTAViewControllerDelegate, CPDFSearchResultsDelegate,CPDFDisplayViewDelegate,CPDFPopMenuDelegate,CPDFThumbnailViewControllerDelegate,CPDFPopMenuViewDelegate,CDocumentPasswordViewControllerDelegate, CPDFPageEditViewControllerDelegate,CPDFAddWatermarkViewControllerDelegate,UIDocumentPickerDelegate, CSearchTitleViewDelegate {
  28. public weak var delegate: CPDFViewBaseControllerDelete?
  29. public var filePath:String?
  30. public var password:String?
  31. public var pdfListView:CPDFListView?
  32. public var popMenu:CPDFPopMenu?
  33. public var navigationTitle:String?
  34. public var titleButton:CNavigationBarTitleButton?
  35. var rightView:CNavigationRightView?
  36. var thumbnailBarItem:UIBarButtonItem?
  37. var backBarItem:UIBarButtonItem?
  38. public var searchToolbar:CSearchToolbar?
  39. public var searchNavView:CSearchTitleView?
  40. public var configuration:CPDFConfiguration?
  41. public var signatures: [CPDFSignature]?
  42. public var documentPickerViewController: UIDocumentPickerViewController?
  43. private var textField: UITextField?
  44. private var isEnterPDFSecurity: Bool = false
  45. public var leftBarButtonItems:[UIBarButtonItem] = []
  46. public var rightBarButtonItems:[UIBarButtonItem] = []
  47. public var navTitieView:UIView?
  48. public var searchOption: CPDFSearchOptions = CPDFSearchOptions(rawValue: 0)
  49. public var functionTypeState: CPDFToolFunctionTypeState = .viewer
  50. public var popSearchReplaceView:CSearchContentView?
  51. public var hightSelection:CPDFSelection?
  52. public init(filePath: String, password: String?) {
  53. super.init(nibName: nil, bundle: nil)
  54. self.filePath = filePath
  55. self.password = password ?? ""
  56. self.configuration = CPDFConfiguration()
  57. let thumbnail = CNavBarButtonItem(viewLeftBarButtonItem: .thumbnail)
  58. let search = CNavBarButtonItem(viewRightBarButtonItem: .search)
  59. let bota = CNavBarButtonItem(viewRightBarButtonItem: .bota)
  60. let more = CNavBarButtonItem(viewRightBarButtonItem: .more)
  61. self.configuration?.showleftItems = [thumbnail]
  62. self.configuration?.showRightItems = [search, bota, more]
  63. }
  64. public init(filePath: String, password: String?, configuration: CPDFConfiguration) {
  65. super.init(nibName: nil, bundle: nil)
  66. self.filePath = filePath
  67. self.password = password ?? ""
  68. self.configuration = configuration
  69. }
  70. required public init?(coder: NSCoder) {
  71. fatalError("init(coder:) has not been implemented")
  72. }
  73. open override func viewDidLoad() {
  74. super.viewDidLoad()
  75. self.automaticallyAdjustsScrollViewInsets = false
  76. view.backgroundColor = CPDFColorUtils.CPDFViewControllerBackgroundColor()
  77. self.initWitPDFListView()
  78. self.initWitNavigation()
  79. self.initWitNavigationTitle()
  80. self.initWithSearchTool()
  81. self.reloadDocument(withFilePath: self.filePath ?? "", password: self.password) { Bool in
  82. }
  83. }
  84. open override func viewDidLayoutSubviews() {
  85. super.viewDidLayoutSubviews()
  86. var height:CGFloat = 0
  87. if self.navigationController?.isNavigationBarHidden != true {
  88. height = self.navigationController?.navigationBar.frame.maxY ?? 0.0
  89. } else {
  90. if #available(iOS 11.0, *) {
  91. height = self.view.safeAreaInsets.top
  92. }
  93. }
  94. if(self.searchToolbar?.superview != nil) {
  95. self.searchToolbar?.frame = CGRect(x: 0, y: height, width: self.view.frame.size.width, height: self.searchToolbar?.frame.height ?? 0)
  96. }
  97. if(popSearchReplaceView?.superview != nil) {
  98. popSearchReplaceView?.frame = CGRect(x: 0, y: self.searchToolbar?.frame.maxY ?? 0, width: self.view.width, height: self.view.height - (self.searchToolbar?.frame.maxY ?? 0))
  99. }
  100. if(self.hightSelection != nil) {
  101. let pageIndex = self.pdfListView?.document.index(for: hightSelection!.page)
  102. self.pdfListView?.go(toPageIndex: Int(pageIndex ?? 0), animated: false)
  103. self.pdfListView?.setHighlightedSelection(self.hightSelection, animated: true)
  104. self.pdfListView?.go(to: self.hightSelection!.bounds, on: self.hightSelection!.page, offsetY: self.searchToolbar?.frame.maxY ?? 0, animated: false)
  105. self.popSearchReplaceView?.setNeedsDisplay()
  106. }
  107. }
  108. func updatePDFViewDocumentView() {
  109. if(self.pdfListView == nil) {
  110. return
  111. }
  112. let documentView = self.pdfListView!.documentView()
  113. if CPDFKitConfig.sharedInstance().displayDirection() == .vertical {
  114. if #available(iOS 11.0, *) {
  115. documentView?.contentInsetAdjustmentBehavior = .automatic
  116. } else {
  117. self.automaticallyAdjustsScrollViewInsets = true
  118. }
  119. } else {
  120. if #available(iOS 11.0, *) {
  121. documentView?.contentInsetAdjustmentBehavior = .never
  122. } else {
  123. self.automaticallyAdjustsScrollViewInsets = false
  124. }
  125. }
  126. }
  127. public lazy var loadingView: CActivityIndicatorView = {
  128. let view = CActivityIndicatorView(style: .gray)
  129. view.center = self.view.center
  130. view.autoresizingMask = [.flexibleTopMargin, .flexibleBottomMargin, .flexibleLeftMargin, .flexibleRightMargin]
  131. return view
  132. }()
  133. func initWitPDFListView() {
  134. self.pdfListView = CPDFListView(frame: self.view.bounds)
  135. self.pdfListView?.performDelegate = self
  136. self.pdfListView?.delegate = self
  137. self.pdfListView?.parentVC = self
  138. self.pdfListView?.configuration = self.configuration
  139. self.pdfListView?.autoresizingMask = [.flexibleWidth, .flexibleHeight]
  140. self.view.addSubview(self.pdfListView!)
  141. CPDFJSONDataParse.initializeAnnotationAttribute(Configuration: self.configuration ?? CPDFConfiguration())
  142. }
  143. public func initWitNavigation() {
  144. let thumbnailItem = UIBarButtonItem(image: UIImage(named: "CPDFThunbnailImageEnter", in: Bundle(for: CPDFViewBaseController.classForCoder()), compatibleWith: nil), style: .plain, target: self, action: #selector(buttonItemClicked_thumbnail(_:)))
  145. let backItem = UIBarButtonItem(image: UIImage(named: "CPDFViewImageBack", in: Bundle(for: CPDFViewBaseController.classForCoder()), compatibleWith: nil), style: .plain, target: self, action: #selector(buttonItemClicked_back(_:)))
  146. self.thumbnailBarItem = thumbnailItem
  147. self.backBarItem = backItem
  148. var leftItems = [UIBarButtonItem]()
  149. for item in self.configuration?.showleftItems ?? [] {
  150. if item.leftBarItem == .back {
  151. leftItems.append(backItem)
  152. } else if item.leftBarItem == .thumbnail {
  153. leftItems.append(thumbnailItem)
  154. }
  155. }
  156. self.navigationItem.leftBarButtonItems = leftItems
  157. var actions = [CNavigationRightAction]()
  158. for item in self.configuration?.showRightItems ?? [] {
  159. if item.rightBarItem == .bota {
  160. let image = UIImage(named: "CNavigationImageNameBota", in: Bundle(for: CPDFViewBaseController.classForCoder()), compatibleWith: nil)
  161. let action = CNavigationRightAction(image: image!, tag: .Bota)
  162. actions.append(action)
  163. } else if item.rightBarItem == .search {
  164. let image = UIImage(named: "CNavigationImageNameSearch", in: Bundle(for: CPDFViewBaseController.classForCoder()), compatibleWith: nil)
  165. let action = CNavigationRightAction(image: image!, tag: .Search)
  166. actions.append(action)
  167. } else if item.rightBarItem == .more {
  168. let image = UIImage(named: "CNavigationImageNameMore", in: Bundle(for: CPDFViewBaseController.classForCoder()), compatibleWith: nil)
  169. let action = CNavigationRightAction(image: image!, tag: .More)
  170. actions.append(action)
  171. }
  172. }
  173. self.rightView = CNavigationRightView(rightActions: actions) { [weak self] tag in
  174. guard let self = self else { return }
  175. switch tag {
  176. case .Search:
  177. self.buttonItemClicked_Search(nil)
  178. case .Bota:
  179. self.buttonItemClicked_Bota(nil)
  180. case .More:
  181. self.buttonItemClicked_More(nil)
  182. }
  183. }
  184. }
  185. func initWithSearchTool() {
  186. if (self.pdfListView != nil) {
  187. self.searchToolbar = CSearchToolbar(pdfView: self.pdfListView!)
  188. self.searchToolbar?.parentVC = self
  189. self.searchToolbar?.delegate = self
  190. }
  191. }
  192. public func enterPDFSetting() {
  193. self.popMenu?.hideMenu()
  194. if (self.pdfListView != nil) {
  195. let displayVc = CPDFDisplayViewController(pdfView: self.pdfListView!)
  196. displayVc.delegate = self
  197. let presentationController = AAPLCustomPresentationController.init(presentedViewController: displayVc, presenting: self)
  198. displayVc.transitioningDelegate = presentationController
  199. self.present(displayVc, animated: true, completion: nil)
  200. }
  201. }
  202. public func enterPDFInfo() {
  203. self.popMenu?.hideMenu()
  204. if (self.pdfListView != nil) {
  205. let infoVc = CPDFInfoViewController(pdfView: self.pdfListView!)
  206. let presentationController = AAPLCustomPresentationController(presentedViewController: infoVc, presenting: self)
  207. infoVc.transitioningDelegate = presentationController
  208. self.present(infoVc, animated: true, completion: nil)
  209. }
  210. }
  211. public func enterPDFShare() {
  212. self.popMenu?.hideMenu()
  213. if (self.pdfListView != nil) {
  214. if self.pdfListView!.isEditing() && self.pdfListView!.isEdited() {
  215. DispatchQueue.global(qos: .default).async {
  216. self.pdfListView!.commitEditing()
  217. let documentFolder = NSHomeDirectory().appending("/Documents/\(self.pdfListView?.document.documentURL.lastPathComponent ?? "")")
  218. let url = URL(fileURLWithPath: documentFolder)
  219. self.pdfListView!.document.write(to: url)
  220. DispatchQueue.main.async {
  221. self.shareAction(url: url)
  222. }
  223. }
  224. } else {
  225. DispatchQueue.global(qos: .default).async {
  226. let documentFolder = NSHomeDirectory().appending("/Documents/\(self.pdfListView!.document.documentURL.lastPathComponent)")
  227. let url = URL(fileURLWithPath: documentFolder)
  228. self.pdfListView!.document.write(to: url)
  229. DispatchQueue.main.async {
  230. self.shareAction(url: url)
  231. }
  232. }
  233. }
  234. }
  235. }
  236. public func enterPDFAddFile() {
  237. self.popMenu?.hideMenu()
  238. let documentTypes = ["com.adobe.pdf"]
  239. documentPickerViewController = UIDocumentPickerViewController(documentTypes: documentTypes, in: .open)
  240. documentPickerViewController?.delegate = self
  241. self.present(documentPickerViewController!, animated: true, completion: nil)
  242. }
  243. public func enterPDFSave() {
  244. self.popMenu?.hideMenu()
  245. if (self.pdfListView?.isEditing() == true && self.pdfListView?.isEdited() == true) {
  246. DispatchQueue.global(qos: .default).async {
  247. self.pdfListView?.commitEditing()
  248. DispatchQueue.main.async {
  249. if self.pdfListView?.document.isModified() == true {
  250. self.pdfListView?.document.write(to: self.pdfListView?.document.documentURL)
  251. let okAction = UIAlertAction(title: NSLocalizedString("OK", comment: ""), style: .cancel, handler: nil)
  252. let alert = UIAlertController(title: NSLocalizedString("Save successfully!", comment: ""), message:"", preferredStyle: .alert)
  253. alert.addAction(okAction)
  254. self.present(alert, animated: true, completion: nil)
  255. } else {
  256. let okAction = UIAlertAction(title: NSLocalizedString("OK", comment: ""), style: .cancel, handler: nil)
  257. let alert = UIAlertController(title: NSLocalizedString("No changes have been made to the document!", comment: ""), message: "", preferredStyle: .alert)
  258. alert.addAction(okAction)
  259. self.present(alert, animated: true, completion: nil)
  260. }
  261. }
  262. }
  263. } else {
  264. if self.pdfListView?.document.isModified() == true {
  265. self.pdfListView?.document.write(to: self.pdfListView?.document.documentURL)
  266. let okAction = UIAlertAction(title: NSLocalizedString("OK", comment: ""), style: .cancel, handler: nil)
  267. let alert = UIAlertController(title: NSLocalizedString("Save successfully!", comment: ""), message:"", preferredStyle: .alert)
  268. alert.addAction(okAction)
  269. present(alert, animated: true, completion: nil)
  270. } else {
  271. let okAction = UIAlertAction(title: NSLocalizedString("OK", comment: ""), style: .cancel, handler: nil)
  272. let alert = UIAlertController(title: NSLocalizedString("No changes have been made to the document!", comment: ""), message: "", preferredStyle: .alert)
  273. alert.addAction(okAction)
  274. present(alert, animated: true, completion: nil)
  275. }
  276. }
  277. }
  278. public func enterPDFFlattened() {
  279. self.popMenu?.hideMenu()
  280. if (!(FileManager.default.fileExists(atPath: TEMPOARTFOLDER))) {
  281. try? FileManager.default.createDirectory(atPath: TEMPOARTFOLDER, withIntermediateDirectories: true, attributes: nil)
  282. }
  283. guard let lastPathComponent = self.pdfListView?.document.documentURL.deletingPathExtension().lastPathComponent else { return }
  284. let secPath = TEMPOARTFOLDER + "/" + lastPathComponent + NSLocalizedString("_Flattened", comment: "") + ".pdf"
  285. do {
  286. try FileManager.default.removeItem(atPath: secPath)
  287. } catch {
  288. // Handle the error, e.g., print an error message or perform other actions
  289. }
  290. let url = NSURL(fileURLWithPath: secPath) as URL
  291. self.pdfListView?.document.writeFlatten(to: url)
  292. shareAction(url: url)
  293. }
  294. public func enterPDFWatermark() {
  295. self.popMenu?.hideMenu()
  296. let addWaterMarkVC = CPDFAddWatermarkViewController.init(fileURL: self.pdfListView?.document.documentURL, document: self.pdfListView?.document)
  297. addWaterMarkVC.delegate = self
  298. self.navigationController?.pushViewController(addWaterMarkVC, animated: false)
  299. }
  300. public func enterPDFSecurity() {
  301. self.popMenu?.hideMenu()
  302. let pdfDocument = CPDFDocument(url:self.pdfListView?.document.documentURL)
  303. if(pdfDocument?.password != nil) {
  304. pdfDocument?.unlock(withPassword: pdfDocument?.password)
  305. }
  306. let filePath = self.pdfListView?.document.documentURL.path ?? ""
  307. // have open PassWord And have open+ower
  308. if pdfDocument != nil && pdfDocument?.isLocked == true {
  309. isEnterPDFSecurity = true
  310. let documentPasswordVC = CDocumentPasswordViewController(document: pdfDocument!)
  311. documentPasswordVC.delegate = self
  312. documentPasswordVC.modalPresentationStyle = .fullScreen
  313. self.present(documentPasswordVC, animated: true, completion: nil)
  314. } else {
  315. if pdfDocument?.permissionsStatus == .user {
  316. enterPermissionPassword(pdfDocument: pdfDocument!)
  317. } else {
  318. enterSecurePDF(filePath: filePath, password: nil)
  319. }
  320. }
  321. }
  322. public func enterSecurePDF(filePath:String,password:String?) {
  323. let secureVC = CPDFSecureViewController(filePath: filePath, password: password)
  324. self.navigationController?.pushViewController(secureVC, animated:true)
  325. }
  326. public func enterPermissionPassword(pdfDocument:CPDFDocument) {
  327. let alert = UIAlertController(title: NSLocalizedString("Enter Owner's Password to Change the Security", comment: ""), message: "", preferredStyle: .alert)
  328. alert.addTextField { (textField) in
  329. let owerPasswordBtton = UIButton(type: .custom)
  330. owerPasswordBtton.addTarget(self, action: #selector(self.buttonItemClicked_showOwerPassword(_:)), for: .touchUpInside)
  331. owerPasswordBtton.setImage(UIImage(named: "CSecureImageInvisible", in: Bundle(for: self.classForCoder), compatibleWith: nil), for: .normal)
  332. owerPasswordBtton.setImage(UIImage(named: "CSecureImageVisible", in: Bundle(for: self.classForCoder), compatibleWith: nil), for: .selected)
  333. owerPasswordBtton.frame = CGRect(x:0, y:0, width:25, height:25)
  334. textField.placeholder = NSLocalizedString("Please enter the owner's password", comment: "")
  335. textField.isSecureTextEntry = true
  336. textField.returnKeyType = .done
  337. textField.rightViewMode = .always
  338. textField.rightView = owerPasswordBtton
  339. self.textField = textField
  340. }
  341. let cancelAction = UIAlertAction(title: NSLocalizedString("Cancel", comment: ""), style: .cancel, handler: nil)
  342. let addAction = UIAlertAction(title: NSLocalizedString("OK", comment: ""), style: .default) { (action) in
  343. if let text = alert.textFields?.first?.text, !text.isEmpty {
  344. let result = pdfDocument.unlock(withPassword: text)
  345. if result == true {
  346. if pdfDocument.permissionsStatus == .owner {
  347. self.enterSecurePDF(filePath: pdfDocument.documentURL.path, password: pdfDocument.password)
  348. } else {
  349. self.enterPermissionPassword(pdfDocument: pdfDocument)
  350. }
  351. } else {
  352. self.enterPermissionPassword(pdfDocument: pdfDocument)
  353. }
  354. } else {
  355. self.enterPermissionPassword(pdfDocument: pdfDocument)
  356. }
  357. }
  358. alert.addAction(cancelAction)
  359. alert.addAction(addAction)
  360. present(alert, animated: true, completion: nil)
  361. }
  362. public func enterPDFPageEdit() {
  363. self.popMenu?.hideMenu()
  364. if (self.pdfListView?.activeAnnotations?.count ?? 0) > 0 {
  365. self.pdfListView?.updateActiveAnnotations([])
  366. self.pdfListView?.setNeedsDisplayForVisiblePages()
  367. }
  368. if (self.pdfListView?.isEditing() == true && self.pdfListView?.isEdited() == true) {
  369. DispatchQueue.global(qos: .default).async {
  370. self.pdfListView?.commitEditing()
  371. DispatchQueue.main.async {
  372. if(self.pdfListView != nil) {
  373. let pageEditViewController = CPDFPageEditViewController(pdfView: self.pdfListView!)
  374. pageEditViewController.pageEditDelegate = self
  375. let navController = CNavigationController(rootViewController: pageEditViewController)
  376. navController.modalPresentationStyle = .fullScreen
  377. self.navigationController?.present(navController, animated: true, completion: nil)
  378. DispatchQueue.main.asyncAfter(deadline: .now() + 0.4) {
  379. pageEditViewController.beginEdit()
  380. }
  381. }
  382. }
  383. }
  384. } else {
  385. if(self.pdfListView != nil) {
  386. let pageEditViewController = CPDFPageEditViewController(pdfView: self.pdfListView!)
  387. pageEditViewController.pageEditDelegate = self
  388. let navController = CNavigationController(rootViewController: pageEditViewController)
  389. navController.modalPresentationStyle = .fullScreen
  390. self.navigationController?.present(navController, animated: true, completion: nil)
  391. DispatchQueue.main.asyncAfter(deadline: .now() + 0.6) {
  392. pageEditViewController.beginEdit()
  393. }
  394. }
  395. }
  396. }
  397. open func initWitNavigationTitle() {
  398. let navTitleButton = CNavigationBarTitleButton()
  399. self.titleButton = navTitleButton
  400. self.navigationTitle = NSLocalizedString("View", comment: "")
  401. if configuration?.availableViewModes.count ?? 0 > 1 {
  402. navTitleButton.setImage(UIImage(named: "syasarrow", in: Bundle(for: CPDFViewBaseController.classForCoder()), compatibleWith: nil), for: .normal)
  403. }
  404. navTitleButton.addTarget(self, action: #selector(titleButtonClickd(_:)), for: .touchUpInside)
  405. navTitleButton.setTitle(self.navigationTitle as String? ?? "", for: .normal)
  406. navTitleButton.setTitleColor(CPDFColorUtils.CAnyReverseBackgooundColor(), for: .normal)
  407. self.titleButton!.frame = CGRect(x: 0, y: 0, width: 100, height: 30)
  408. self.navigationItem.titleView = self.titleButton
  409. }
  410. open func reloadDocument(withFilePath filePath: String, password: String?, completion: @escaping (Bool) -> Void) {
  411. navigationController?.view.isUserInteractionEnabled = false
  412. if loadingView.superview == nil {
  413. view.addSubview(self.loadingView)
  414. }
  415. self.loadingView.startAnimating()
  416. DispatchQueue.global(qos: .default).async {
  417. let url = URL(fileURLWithPath: filePath)
  418. let document = CPDFDocument(url: url)
  419. if document?.isLocked == true {
  420. document?.unlock(withPassword: password)
  421. }
  422. DispatchQueue.main.async {
  423. self.navigationController?.view.isUserInteractionEnabled = true
  424. self.loadingView.stopAnimating()
  425. self.loadingView.removeFromSuperview()
  426. if let error = document?.error, error._code != CPDFDocumentPasswordError {
  427. let okAction = UIAlertAction(title: NSLocalizedString("OK", comment: ""), style: .default) { _ in
  428. self.navigationController?.popViewController(animated: true)
  429. }
  430. let alert = UIAlertController(title: "", message: NSLocalizedString("Sorry PDF Reader Can't open this pdf file!", comment: ""), preferredStyle: .alert)
  431. alert.addAction(okAction)
  432. self.present(alert, animated: true, completion: nil)
  433. completion(false)
  434. } else {
  435. self.pdfListView?.document = document
  436. completion(true)
  437. }
  438. }
  439. }
  440. }
  441. func removeSearchContent() {
  442. if(popSearchReplaceView?.superview != nil) {
  443. popSearchReplaceView?.removeFromSuperview()
  444. popSearchReplaceView = nil
  445. }
  446. self.hightSelection = nil
  447. }
  448. func addSearcchContent() {
  449. if(popSearchReplaceView == nil && self.pdfListView != nil) {
  450. popSearchReplaceView = CSearchContentView(pdfView: self.pdfListView!)
  451. popSearchReplaceView?.frame = CGRect(x: 0, y: self.searchToolbar?.frame.maxY ?? 0, width: self.view.width, height: self.view.height - (self.searchToolbar?.frame.maxY ?? 0))
  452. if(popSearchReplaceView != nil) {
  453. self.view.addSubview(popSearchReplaceView!)
  454. }
  455. }
  456. popSearchReplaceView?.callback = { [weak self] in
  457. guard let currentSelection = self?.hightSelection else { return }
  458. let result = self?.pdfListView?.document.replace(with: currentSelection, search: self?.searchToolbar?.searchKeyString ?? "", toReplace: self?.searchToolbar?.replaceTextFied.text) { newSelection in
  459. self?.pdfListView?.setHighlightedSelection(newSelection, animated: true)
  460. self?.hightSelection = newSelection
  461. self?.pdfListView?.setNeedsDisplayFor(currentSelection.page)
  462. self?.popSearchReplaceView?.updateSelection(nil)
  463. }
  464. }
  465. popSearchReplaceView?.updateSelection(hightSelection)
  466. }
  467. // MARK: - CPDFPageEditViewControllerDelegate
  468. open func pageEditViewControllerDone(_ pageEditViewController: CPDFPageEditViewController) {
  469. pageEditViewController.dismiss(animated: true) {
  470. if pageEditViewController.isPageEdit {
  471. self.reloadDocument(withFilePath: (self.filePath)!, password: self.pdfListView?.document.password) { [weak self] result in
  472. self?.pdfListView?.reloadInputViews()
  473. self?.selectDocumentRefresh()
  474. }
  475. self.pdfListView?.reloadInputViews()
  476. }
  477. }
  478. }
  479. open func pageEditViewController(_ pageEditViewController: CPDFPageEditViewController, pageIndex: Int, isPageEdit: Bool) {
  480. if isPageEdit {
  481. reloadDocument(withFilePath: self.filePath!, password: nil) { [weak self] result in
  482. self?.pdfListView?.reloadInputViews()
  483. self?.pdfListView?.go(toPageIndex: pageIndex, animated: false)
  484. self?.selectDocumentRefresh()
  485. }
  486. } else {
  487. self.pdfListView?.go(toPageIndex: pageIndex, animated: false)
  488. }
  489. }
  490. // MARK: - CPDFAddWatermarkViewControllerDelegate
  491. open func addWatermarkViewControllerSave(_ addWatermarkViewControllerSave: CPDFAddWatermarkViewController, Text textWaterModel: CWatermarkModel) {
  492. }
  493. open func addWatermarkViewControllerSave(_ addWatermarkViewControllerSave: CPDFAddWatermarkViewController, Image imageWaterModel: CWatermarkModel) {
  494. }
  495. // MARK: - Action
  496. @objc func buttonItemClicked_showOwerPassword(_ button: UIButton) {
  497. if button.isSelected == true {
  498. button.isSelected = false
  499. textField?.isSecureTextEntry = true
  500. } else {
  501. button.isSelected = true
  502. textField?.isSecureTextEntry = false
  503. }
  504. }
  505. open func setTitleRefresh() {
  506. }
  507. open func selectDocumentRefresh() {
  508. }
  509. open func shareRefresh() {
  510. }
  511. @objc open func buttonItemClicked_Search(_ button: UIButton?) {
  512. if(self.navigationController?.navigationBar != nil) {
  513. if (self.pdfListView != nil) {
  514. self.searchNavView = CSearchTitleView(pdfView: self.pdfListView!)
  515. self.searchNavView?.delegate = self
  516. }
  517. self.searchToolbar?.show(in: self.view)
  518. self.searchToolbar?.searchTitleType = .search
  519. self.searchToolbar?.searchOption = searchOption
  520. self.navigationTitle = ""
  521. self.navTitieView = self.navigationItem.titleView
  522. self.leftBarButtonItems = self.navigationItem.leftBarButtonItems!
  523. self.rightBarButtonItems = self.navigationItem.rightBarButtonItems!
  524. self.navigationController?.title = NSLocalizedString("Search", comment: "")
  525. let settingItem = UIBarButtonItem(image: UIImage(named: "CPDFSearchImageSetting", in: Bundle(for: CPDFViewBaseController.classForCoder()), compatibleWith: nil), style: .plain, target: self, action: #selector(buttonItemClicked_searchSetting(_:)))
  526. let searchBackItem = UIBarButtonItem(image: UIImage(named: "CPDFViewImageBack", in: Bundle(for: CPDFViewBaseController.classForCoder()), compatibleWith: nil), style: .plain, target: self, action: #selector(buttonItemClicked_searchBack(_:)))
  527. self.navigationItem.rightBarButtonItems = [settingItem]
  528. self.navigationItem.leftBarButtonItems = [searchBackItem]
  529. self.navigationItem.titleView = self.searchNavView
  530. }
  531. if(self.pdfListView?.toolModel == .edit) {
  532. addSearcchContent()
  533. }
  534. var inset:UIEdgeInsets = self.pdfListView?.documentView().contentInset ?? UIEdgeInsets.zero
  535. inset.top += searchToolbar?.height ?? 0
  536. self.pdfListView?.documentView().contentInset = inset
  537. }
  538. @objc open func buttonItemClicked_Bota(_ button: UIButton?) {
  539. if(self.pdfListView != nil) {
  540. let botaViewController = CPDFBOTAViewController(pdfView: self.pdfListView!)
  541. botaViewController.delegate = self
  542. let presentationController = AAPLCustomPresentationController(presentedViewController: botaViewController, presenting: self)
  543. botaViewController.transitioningDelegate = presentationController
  544. self.present(botaViewController, animated: true, completion: nil)
  545. }
  546. }
  547. @objc open func buttonItemClicked_More(_ button: UIButton?) {
  548. if (self.configuration?.showMoreItems.count ?? 0) > 0 {
  549. let menuView = CPDFPopMenuView.init(CGRect(x: 0, y: 0, width: 200, height: CGFloat((self.configuration?.showMoreItems.count ?? 0) * 45) + 20), Configuration: self.configuration ?? CPDFConfiguration())
  550. menuView.delegate = self
  551. self.popMenu = CPDFPopMenu(contentView: menuView)
  552. self.popMenu?.dimCoverLayer = true
  553. self.popMenu?.delegate = self
  554. if #available(iOS 11.0, *) {
  555. self.popMenu?.showMenu(in: CGRect(x: self.view.frame.size.width - self.view.safeAreaInsets.right - 250, y: (self.navigationController?.navigationBar.frame)?.maxY ?? 0, width: 250, height: CGFloat((self.configuration?.showMoreItems.count ?? 0) * 45) + 20))
  556. } else {
  557. self.popMenu?.showMenu(in: CGRect(x: self.view.frame.size.width - 250, y: (self.navigationController?.navigationBar.frame)?.maxY ?? 0, width: 250, height: CGFloat((self.configuration?.showMoreItems.count ?? 0) * 45) + 20))
  558. }
  559. }
  560. }
  561. @objc open func buttonItemClicked_thumbnail(_ button: UIButton) {
  562. if (self.pdfListView?.activeAnnotations?.count ?? 0) > 0 {
  563. self.pdfListView?.updateActiveAnnotations([])
  564. self.pdfListView?.setNeedsDisplayForVisiblePages()
  565. }
  566. if (self.pdfListView?.isEditing() == true && self.pdfListView?.isEdited() == true) {
  567. DispatchQueue.global(qos: .default).async {
  568. self.pdfListView?.commitEditing()
  569. DispatchQueue.main.async {
  570. self.enterThumbnail()
  571. }
  572. }
  573. } else {
  574. enterThumbnail()
  575. }
  576. }
  577. open func enterThumbnail() {
  578. let thumbnailViewController = CPDFThumbnailViewController(pdfView: self.pdfListView!)
  579. thumbnailViewController.delegate = self
  580. let presentationController = AAPLCustomPresentationController(presentedViewController: thumbnailViewController, presenting: self)
  581. thumbnailViewController.transitioningDelegate = presentationController
  582. let nav = UINavigationController(rootViewController: thumbnailViewController)
  583. self.present(nav, animated: true, completion: nil)
  584. }
  585. @objc func buttonItemClicked_back(_ button: UIButton) {
  586. if (self.pdfListView?.isEditing() == true && self.pdfListView?.isEdited() == true) {
  587. DispatchQueue.global(qos: .default).async {
  588. self.pdfListView?.commitEditing()
  589. DispatchQueue.main.async {
  590. if self.pdfListView?.document.isModified() == true {
  591. self.pdfListView?.document.write(to: self.pdfListView?.document.documentURL)
  592. }
  593. self.delegate?.PDFViewBaseControllerDissmiss?(self)
  594. }
  595. }
  596. } else {
  597. if(self.pdfListView?.document != nil) {
  598. if self.pdfListView?.document.isModified() == true {
  599. self.pdfListView?.document.write(to: self.pdfListView?.document.documentURL)
  600. }
  601. }
  602. self.delegate?.PDFViewBaseControllerDissmiss?(self)
  603. }
  604. }
  605. @objc open func titleButtonClickd(_ button: UIButton) {
  606. }
  607. @objc open func buttonItemClicked_searchSetting(_ button: UIButton) {
  608. var isSensitive = true
  609. if searchOption.contains(.caseSensitive) {
  610. // Your code here
  611. isSensitive = false
  612. }
  613. var isWholeWord = false
  614. if searchOption.contains(.matchWholeWord) {
  615. // Your code here
  616. isWholeWord = true
  617. }
  618. let searchSettingController = CSearchSettingViewController(isSensitive: isSensitive, isWholeWord: isWholeWord)
  619. let nav = CNavigationController(rootViewController: searchSettingController)
  620. let presentationController = AAPLCustomPresentationController(presentedViewController: nav, presenting: self)
  621. weak var weakBlockSelf = self
  622. searchSettingController.callback = { [weak weakBlockSelf] searchOptionz in
  623. if(weakBlockSelf?.searchOption != searchOptionz) {
  624. weakBlockSelf?.searchOption = searchOptionz
  625. weakBlockSelf?.searchToolbar?.searchOption = searchOptionz
  626. weakBlockSelf?.searchToolbar?.clearDatas(false)
  627. }
  628. }
  629. nav.transitioningDelegate = presentationController
  630. self.present(nav, animated: true, completion: nil)
  631. }
  632. @objc open func buttonItemClicked_searchBack(_ button: UIButton?) {
  633. if ((searchNavView?.superview) != nil) {
  634. searchNavView?.removeFromSuperview()
  635. self.title = self.navigationTitle as String?
  636. self.navigationItem.leftBarButtonItems = self.leftBarButtonItems
  637. self.navigationItem.rightBarButtonItems = self.rightBarButtonItems
  638. self.navigationItem.titleView = self.navTitieView
  639. }
  640. var inset:UIEdgeInsets = self.pdfListView?.documentView().contentInset ?? UIEdgeInsets.zero
  641. inset.top = 0
  642. self.pdfListView?.documentView().contentInset = inset
  643. if(searchToolbar?.superview != nil) {
  644. searchToolbar?.removeFromSuperview()
  645. }
  646. removeSearchContent()
  647. self.navigationTitle? = NSLocalizedString("Viewer", comment: "")
  648. self.searchToolbar?.clearDatas(true)
  649. }
  650. // MARK: - CPDFViewDelegate
  651. open func pdfViewDocumentDidLoaded(_ pdfView: CPDFView!) {
  652. if(self.rightView != nil){
  653. let rightItem = UIBarButtonItem(customView: self.rightView!)
  654. self.navigationItem.rightBarButtonItems = [rightItem]
  655. }
  656. self.updatePDFViewDocumentView()
  657. //Avoid jumping back to the first page when it is not the first page (because the same PDFView display is used)
  658. if(self.pdfListView?.currentPageIndex != 0) {
  659. self.pdfListView?.go(toPageIndex: 0, animated: false)
  660. }
  661. self.loadingView.startAnimating()
  662. let signatures = self.pdfListView?.document.signatures() ?? []
  663. var mSignatures: [CPDFSignature] = []
  664. for sign in signatures {
  665. if sign.signers.count > 0 {
  666. mSignatures.append(sign)
  667. }
  668. }
  669. self.signatures = mSignatures
  670. self.navigationController?.view.isUserInteractionEnabled = true
  671. self.loadingView.stopAnimating()
  672. self.loadingView.removeFromSuperview()
  673. CPDFJSONDataParse.initializeReaderViewConfig(self.configuration ?? CPDFConfiguration(), PDFView: pdfListView ?? CPDFListView(frame: .zero))
  674. }
  675. open func pdfViewCurrentPageDidChanged(_ pdfView: CPDFView!) {
  676. self.updatePDFViewDocumentView()
  677. }
  678. open func pdfViewPerformURL(_ pdfView: CPDFView!, withContent content: String!) {
  679. if let url = URL(string: content) {
  680. UIApplication.shared.open(url)
  681. } else {
  682. let cancelAction = UIAlertAction(title: NSLocalizedString("OK", comment: ""), style: .cancel, handler: nil)
  683. let alert = UIAlertController(title: NSLocalizedString("Error", comment: ""), message: NSLocalizedString("The hyperlink is invalid.", comment: ""), preferredStyle: .alert)
  684. alert.addAction(cancelAction)
  685. self.present(alert, animated: true, completion: nil)
  686. }
  687. }
  688. open func pdfViewPerformReset(_ pdfView: CPDFView!) {
  689. let okAction = UIAlertAction(title: NSLocalizedString("Yes", comment: ""), style: .default) { (action) in
  690. self.pdfListView?.document.resetForm()
  691. self.pdfListView?.setNeedsDisplayForVisiblePages()
  692. }
  693. let cancelAction = UIAlertAction(title: NSLocalizedString("No", comment: ""), style: .cancel, handler: nil)
  694. let alert = UIAlertController(title: nil, message: String(format: NSLocalizedString("Do you really want to reset the form?", comment: "")), preferredStyle: .alert)
  695. alert.addAction(okAction)
  696. alert.addAction(cancelAction)
  697. self.present(alert, animated: true, completion: nil)
  698. }
  699. open func pdfViewPerformPrint(_ pdfView: CPDFView!) {
  700. print("Print")
  701. }
  702. open func pdfViewEditingSelectStateDidChanged(_ pdfView: CPDFView) {
  703. }
  704. open func pdfViewShouldBeginEditing(_ pdfView: CPDFView, textView: UITextView, for annotation: CPDFFreeTextAnnotation) {
  705. }
  706. open func pdfViewEditingAddTextArea(_ pdfView: CPDFView, add page: CPDFPage, add rect: CGRect) {
  707. }
  708. open func pdfViewEditingAddImageArea(_ pdfView: CPDFView, add page: CPDFPage, add rect: CGRect) {
  709. }
  710. // MARK: - CPDFListViewDelegate
  711. open func PDFListViewPerformTouchEnded(_ pdfListView: CPDFListView) {
  712. }
  713. open func PDFListViewEditNote(_ pdfListView: CPDFListView, forAnnotation annotation: CPDFAnnotation) {
  714. }
  715. open func PDFListViewChangedAnnotationType(_ pdfListView: CPDFListView, forAnnotationMode annotationMode: Int) {
  716. }
  717. open func PDFListViewPerformAddStamp(_ pdfView: CPDFListView, atPoint point: CGPoint, forPage page: CPDFPage) {
  718. }
  719. open func PDFListViewPerformAddImage(_ pdfView: CPDFListView, atPoint point: CGPoint, forPage page: CPDFPage) {
  720. }
  721. open func PDFListViewerTouchEndedIsAudioRecordMedia(_ pdfListView: CPDFListView) -> Bool {
  722. return false
  723. }
  724. open func PDFListViewPerformCancelMedia(_ pdfView: CPDFListView, atPoint point: CGPoint, forPage page: CPDFPage) {
  725. }
  726. open func PDFListViewPerformRecordMedia(_ pdfView: CPDFListView, atPoint point: CGPoint, forPage page: CPDFPage) {
  727. }
  728. open func PDFListViewPerformPlay(_ pdfView: CPDFListView, forAnnotation annotation: CPDFSoundAnnotation) {
  729. }
  730. open func PDFListViewPerformSignatureWidget(_ pdfView: CPDFListView, forAnnotation annotation: CPDFSignatureWidgetAnnotation) {
  731. }
  732. open func PDFListViewEditProperties(_ pdfListView: CPDFListView, forAnnotation annotation: CPDFAnnotation) {
  733. }
  734. open func PDFListViewContentEditProperty(_ pdfListView: CPDFListView, point: CGPoint) {
  735. }
  736. // MARK: - CSearchToolbarDelegate
  737. open func searchToolbar(_ searchToolbar: CSearchToolbar, onSearchQueryResults results: [Any]) {
  738. if results.count < 1 {
  739. let cancelAction = UIAlertAction(title: NSLocalizedString("OK", comment: ""), style: .cancel, handler: nil)
  740. let alert = UIAlertController(title: nil, message: NSLocalizedString("Your search returned no results.", comment: ""), preferredStyle: .alert)
  741. alert.addAction(cancelAction)
  742. self.present(alert, animated: true, completion: nil)
  743. return
  744. }
  745. if self.pdfListView?.document != nil {
  746. let searchResultController = CPDFSearchResultsViewController(resultArray: results, keyword: searchToolbar.searchKeyString, document: self.pdfListView!.document)
  747. searchResultController.pdfListView = self.pdfListView
  748. searchResultController.searchString = searchToolbar.searchKeyString
  749. searchResultController.delegate = self
  750. let nav = CNavigationController(rootViewController: searchResultController)
  751. nav.modalPresentationStyle = .fullScreen
  752. self.present(nav, animated: true, completion: nil)
  753. }
  754. }
  755. open func searchToolbarReplace(_ searchToolbar: CSearchToolbar) {
  756. buttonItemClicked_searchBack(nil)
  757. self.pdfListView?.setNeedsDisplayForVisiblePages()
  758. }
  759. open func searchToolbarTextChange(_ searchToolbar: CSearchToolbar) {
  760. self.hightSelection = nil
  761. }
  762. open func searchToolbarChangeSelection(_ searchToolbar: CSearchToolbar, changeSelection selection: CPDFSelection?) {
  763. if(selection != nil) {
  764. let offset = searchToolbar.frame.maxY
  765. let pageIndex = self.pdfListView?.document.index(for: selection!.page)
  766. self.pdfListView?.go(toPageIndex: Int(pageIndex ?? 0), animated: false)
  767. self.pdfListView?.go(to: selection!.bounds, on: selection!.page, offsetY: offset, animated: false)
  768. }
  769. self.pdfListView?.setHighlightedSelection(selection, animated: true)
  770. self.hightSelection = selection
  771. if self.searchToolbar?.searchTitleType == .replace {
  772. self.popSearchReplaceView?.updateSelection(selection)
  773. } else {
  774. self.popSearchReplaceView?.updateSelection(nil)
  775. }
  776. }
  777. // MARK: - CPDFDisplayViewDelegate
  778. func displayViewControllerDismiss(_ displayViewController: CPDFDisplayViewController) {
  779. self.navigationController?.dismiss(animated: true,completion: {
  780. })
  781. }
  782. // MARK: - CPDFBOTAViewControllerDelegate
  783. open func botaViewControllerDismiss(_ botaViewController: CPDFBOTAViewController) {
  784. self.navigationController?.dismiss(animated: true,completion: {
  785. })
  786. }
  787. // MARK: - CPDFSearchResultsDelegate
  788. func searchResultsView(_ resultVC: CPDFSearchResultsViewController, forSelection selection: CPDFSelection, indexPath: IndexPath) {
  789. if searchToolbar != nil {
  790. searchToolbarChangeSelection(searchToolbar!, changeSelection: selection)
  791. }
  792. }
  793. func searchResultsViewControllerDismiss(_ searchResultsViewController: CPDFSearchResultsViewController) {
  794. searchResultsViewController.dismiss(animated: true) {
  795. }
  796. }
  797. // MARK: - CPDFPopMenuDelegate
  798. open func menuDidClosed(in menu: CPDFPopMenu, isClosed: Bool) {
  799. }
  800. // MARK: - CPDFThumbnailViewControllerDelegate
  801. open func thumbnailViewController(_ thumbnailViewController: CPDFThumbnailViewController, pageIndex: Int) {
  802. thumbnailViewController.dismiss(animated: true) {
  803. self.pdfListView?.go(toPageIndex: pageIndex, animated: true)
  804. }
  805. }
  806. open func thumbnailViewControllerDismiss(_ thumbnailViewController: CPDFThumbnailViewController) {
  807. thumbnailViewController.dismiss(animated: true,completion: nil)
  808. }
  809. // MARK: - CPDFPopMenuViewDelegate
  810. public func menuDidClick(at view: CPDFPopMenuView, clickType viewType: CPDFPopMenuViewType) {
  811. switch viewType {
  812. case .setting:
  813. enterPDFSetting()
  814. case .pageEdit:
  815. enterPDFPageEdit()
  816. case .info:
  817. enterPDFInfo()
  818. case .share:
  819. enterPDFShare()
  820. case .addFile:
  821. enterPDFAddFile()
  822. case .save:
  823. enterPDFSave()
  824. case .watermark:
  825. enterPDFWatermark()
  826. case .security:
  827. enterPDFSecurity()
  828. case .flattened:
  829. enterPDFFlattened()
  830. }
  831. }
  832. func shareAction(url: URL) {
  833. let activityVC = UIActivityViewController(activityItems: [url], applicationActivities: nil)
  834. activityVC.definesPresentationContext = true
  835. if UI_USER_INTERFACE_IDIOM() == .pad {
  836. activityVC.popoverPresentationController?.sourceView = self.rightView
  837. activityVC.popoverPresentationController?.sourceRect = CGRect(x: (self.rightView?.bounds.origin.x) ?? 0 + ((self.rightView?.bounds.size.width) ?? 0)/3*2 + 10, y: self.rightView?.bounds.maxY ?? 0, width: 1, height: 1)
  838. }
  839. self.present(activityVC, animated: true, completion: nil)
  840. activityVC.completionWithItemsHandler = { (activityType, completed, returnedItems, activityError) in
  841. if completed {
  842. print("Success!")
  843. } else {
  844. print("Failed Or Canceled!")
  845. }
  846. }
  847. }
  848. open func searchTitleViewChangeType(_ searchTitleView: CSearchTitleView, onChange searchType: Int) {
  849. var inset:UIEdgeInsets = self.pdfListView?.documentView().contentInset ?? UIEdgeInsets.zero
  850. if(self.searchToolbar?.superview != nil) {
  851. self.searchToolbar?.searchTitleType = CSearchTitleType(rawValue: searchType) ?? .search
  852. }
  853. inset.top = searchToolbar?.height ?? 0
  854. self.pdfListView?.documentView().contentInset = inset
  855. if searchToolbar != nil, hightSelection != nil {
  856. searchToolbarChangeSelection(searchToolbar!, changeSelection: hightSelection)
  857. } else if searchToolbar != nil, hightSelection == nil {
  858. if let text = searchToolbar?.searchBar.text, !text.isEmpty {
  859. searchToolbar?.searchButton.setTitleColor(CPDFColorUtils.CPageEditToolbarFontColor(), for: .normal)
  860. searchToolbar?.searchButton.isEnabled = true
  861. }
  862. }
  863. }
  864. // MARK: - UIDocumentPickerDelegate
  865. open func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
  866. let fileUrlAuthozied = urls.first?.startAccessingSecurityScopedResource() ?? false
  867. if fileUrlAuthozied {
  868. if self.pdfListView!.isEditing() == true {
  869. DispatchQueue.global(qos: .default).async {
  870. if self.pdfListView!.isEdited() == true {
  871. self.pdfListView!.commitEditing()
  872. }
  873. DispatchQueue.main.async {
  874. self.pdfListView!.endOfEditing()
  875. DispatchQueue.global(qos: .default).async {
  876. if self.pdfListView!.document.isModified() {
  877. self.pdfListView!.document.write(to: self.pdfListView!.document.documentURL)
  878. }
  879. DispatchQueue.main.async {
  880. self.openFile(with: urls)
  881. }
  882. }
  883. }
  884. }
  885. } else {
  886. DispatchQueue.global(qos: .default).async {
  887. if self.pdfListView!.document.isModified() == true {
  888. self.pdfListView!.document.write(to: self.pdfListView!.document.documentURL)
  889. }
  890. DispatchQueue.main.async {
  891. self.openFile(with: urls)
  892. }
  893. }
  894. }
  895. }
  896. }
  897. open func openFile(with urls: [URL]) {
  898. let fileCoordinator = NSFileCoordinator()
  899. var error: NSError?
  900. fileCoordinator.coordinate(readingItemAt: urls.first!, options: [], error: &error) { newURL in
  901. let documentFolder = NSHomeDirectory().appending("/Documents/Files")
  902. if !FileManager.default.fileExists(atPath: documentFolder) {
  903. try? FileManager.default.createDirectory(at: URL(fileURLWithPath: documentFolder), withIntermediateDirectories: true, attributes: nil)
  904. }
  905. let documentPath = documentFolder + "/\(newURL.lastPathComponent)"
  906. if !FileManager.default.fileExists(atPath: documentPath) {
  907. try? FileManager.default.copyItem(atPath: newURL.path, toPath: documentPath)
  908. }
  909. let url = URL(fileURLWithPath: documentPath)
  910. let document = CPDFDocument(url: url)
  911. self.filePath = documentPath
  912. if document?.error != nil && document?.error._code != CPDFDocumentPasswordError {
  913. let okAction = UIAlertAction(title: NSLocalizedString("OK", comment: ""), style: .default) { (action) in
  914. }
  915. let alert = UIAlertController(title: "", message: NSLocalizedString("Sorry PDF Reader Can't open this pdf file!", comment: ""), preferredStyle: .alert)
  916. alert.addAction(okAction)
  917. let tRootViewControl = self
  918. tRootViewControl.present(alert, animated: true, completion: nil)
  919. } else {
  920. if document?.isLocked == true {
  921. let documentPasswordVC = CDocumentPasswordViewController(document: document!)
  922. documentPasswordVC.delegate = self
  923. documentPasswordVC.modalPresentationStyle = .fullScreen
  924. let tRootViewControl = self
  925. tRootViewControl.present(documentPasswordVC, animated: true, completion: nil)
  926. } else {
  927. self.pdfListView?.updateActiveAnnotations([])
  928. self.pdfListView?.document = document
  929. self.pdfListView?.registerAsObserver()
  930. self.selectDocumentRefresh()
  931. self.setTitleRefresh()
  932. }
  933. }
  934. }
  935. urls.first?.stopAccessingSecurityScopedResource()
  936. }
  937. open func documentPickerWasCancelled(_ controller: UIDocumentPickerViewController) {
  938. }
  939. // MARK: - CDocumentPasswordViewControllerDelegate
  940. open func documentPasswordViewControllerOpen(_ documentPasswordViewController: CDocumentPasswordViewController, document: CPDFDocument) {
  941. if(isEnterPDFSecurity) {
  942. if document.permissionsStatus == .owner {
  943. enterSecurePDF(filePath: document.documentURL.path, password: document.password)
  944. } else {
  945. enterPermissionPassword(pdfDocument: document)
  946. }
  947. isEnterPDFSecurity = false
  948. } else {
  949. self.pdfListView?.document = document;
  950. self.selectDocumentRefresh()
  951. self.setTitleRefresh()
  952. }
  953. }
  954. open func documentPasswordViewControllerCancel(_ documentPasswordViewController: CDocumentPasswordViewController) {
  955. isEnterPDFSecurity = false
  956. if self.pdfListView?.toolModel == .edit {
  957. self.pdfListView?.beginEditingLoadType([.text, .image])
  958. self.pdfListView?.setShouAddEdit([])
  959. }
  960. }
  961. }