RCTCPDFView.swift 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811
  1. //
  2. // RCTCPDFView.swift
  3. // react-native-compdfkit-pdf
  4. //
  5. // Copyright © 2014-2025 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_Tools
  14. import ComPDFKit
  15. protocol RCTCPDFViewDelegate: AnyObject {
  16. func cpdfViewAttached(_ cpdfView: RCTCPDFView)
  17. func saveDocumentChange(_ cpdfView: RCTCPDFView)
  18. func onPageChanged(_ cpdfView: RCTCPDFView, pageIndex: Int)
  19. }
  20. class RCTCPDFView: UIView, CPDFViewBaseControllerDelete {
  21. weak var delegate: RCTCPDFViewDelegate?
  22. public var pdfViewController : CPDFViewController?
  23. private var navigationController : CNavigationController?
  24. init() {
  25. super.init(frame: CGRect(x: 0, y: 0, width: 500, height: 400))
  26. }
  27. required init?(coder: NSCoder) {
  28. fatalError("init(coder:) has not been implemented")
  29. }
  30. // MARK: - Private Methods
  31. private func createCPDFView() {
  32. var documentPath = document.path
  33. var success = false
  34. let homeDiectory = NSHomeDirectory()
  35. let bundlePath = Bundle.main.bundlePath
  36. if (documentPath.hasPrefix(homeDiectory) || documentPath.hasPrefix(bundlePath)) {
  37. let documentHome = homeDiectory.appending("/Documents")
  38. if documentPath.hasPrefix(homeDiectory) && documentPath.hasPrefix(documentHome) {
  39. } else {
  40. let fileManager = FileManager.default
  41. let samplesFilePath = NSHomeDirectory().appending("/Documents/Files")
  42. let fileName = document.lastPathComponent
  43. let docsFilePath = samplesFilePath + "/" + fileName
  44. if !fileManager.fileExists(atPath: samplesFilePath) {
  45. try? FileManager.default.createDirectory(atPath: samplesFilePath, withIntermediateDirectories: true, attributes: nil)
  46. }
  47. try? FileManager.default.copyItem(atPath: document.path, toPath: docsFilePath)
  48. documentPath = docsFilePath
  49. }
  50. } else {
  51. success = document.startAccessingSecurityScopedResource()
  52. }
  53. let jsonData = CPDFJSONDataParse(String: configuration)
  54. let configurations = jsonData.configuration ?? CPDFConfiguration()
  55. pdfViewController = CPDFViewController(filePath: documentPath, password: password, configuration: configurations)
  56. pdfViewController?.delegate = self
  57. navigationController = CNavigationController(rootViewController: pdfViewController!)
  58. navigationController?.view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
  59. navigationController?.view.frame = self.frame
  60. navigationController?.setViewControllers([pdfViewController!], animated: true)
  61. addSubview(navigationController?.view ?? UIView())
  62. self.delegate?.cpdfViewAttached(self)
  63. if success {
  64. document.stopAccessingSecurityScopedResource()
  65. }
  66. }
  67. func insertPDFDocument(_ document: CPDFDocument, Pages pages: [Int], Position index: UInt) -> Bool {
  68. if let pdfListView = self.pdfViewController?.pdfListView {
  69. var _index: UInt = index
  70. if index < 0 || index > pdfListView.document.pageCount {
  71. if Int(index) == -1 {
  72. _index = pdfListView.document.pageCount
  73. } else {
  74. return false
  75. }
  76. }
  77. var indexSet = IndexSet()
  78. for page in pages {
  79. indexSet.insert(IndexSet.Element(page))
  80. }
  81. let success = pdfListView.document.importPages(indexSet, from: document, at: _index)
  82. pdfListView.layoutDocumentView()
  83. return success
  84. } else {
  85. return false
  86. }
  87. }
  88. func extractPDFDocument(_ savePath: URL, Pages pages: [Int]) -> Bool {
  89. if let pdfListView = self.pdfViewController?.pdfListView {
  90. var indexSet = IndexSet()
  91. for page in pages {
  92. indexSet.insert(page)
  93. }
  94. let document = CPDFDocument()
  95. document?.importPages(indexSet, from: pdfListView.document, at: 0)
  96. let success = document?.write(to: savePath, isSaveFontSubset: true) ?? false
  97. return success
  98. } else {
  99. return false
  100. }
  101. }
  102. func getValue<T>(from info: [String: Any]?, key: String, defaultValue: T) -> T {
  103. guard let value = info?[key] as? T else {
  104. return defaultValue
  105. }
  106. return value
  107. }
  108. // MARK: - Page Public Methods
  109. func getPage(_ index: UInt) -> CPDFPage {
  110. if let pdfListView = self.pdfViewController?.pdfListView {
  111. let page = pdfListView.document.page(at: index) ?? CPDFPage()
  112. return page
  113. } else {
  114. return CPDFPage()
  115. }
  116. }
  117. // MARK: - Document Public Methods
  118. func saveDocument(completionHandler: @escaping (Bool) -> Void) {
  119. if (self.pdfViewController?.pdfListView?.isEditing() == true && self.pdfViewController?.pdfListView?.isEdited() == true) {
  120. DispatchQueue.global(qos: .default).async {
  121. if self.pdfViewController?.pdfListView?.isEdited() == true {
  122. self.pdfViewController?.pdfListView?.commitEditing()
  123. }
  124. DispatchQueue.main.async {
  125. if self.pdfViewController?.pdfListView?.document.isModified() == true {
  126. let document = self.pdfViewController?.pdfListView?.document
  127. let success = document?.write(to: document?.documentURL ?? URL(fileURLWithPath: ""), isSaveFontSubset: true) ?? false
  128. completionHandler(success)
  129. } else {
  130. completionHandler(true)
  131. }
  132. }
  133. }
  134. } else {
  135. if self.pdfViewController?.pdfListView?.document.isModified() == true {
  136. let document = self.pdfViewController?.pdfListView?.document
  137. let success = document?.write(to: document?.documentURL ?? URL(fileURLWithPath: ""), isSaveFontSubset: true) ?? false
  138. completionHandler(success)
  139. } else {
  140. completionHandler(true)
  141. }
  142. }
  143. }
  144. func setMargins(left : Int, top : Int, right : Int, bottom : Int) {
  145. if let pdfListView = self.pdfViewController?.pdfListView {
  146. pdfListView.pageBreakMargins = .init(top: CGFloat(top), left: CGFloat(left), bottom: CGFloat(bottom), right: CGFloat(right))
  147. pdfListView.layoutDocumentView()
  148. }
  149. }
  150. func removeAllAnnotations(completionHandler: @escaping (Bool) -> Void) {
  151. if let pdfListView = self.pdfViewController?.pdfListView {
  152. let pageCount = pdfListView.document?.pageCount ?? 0
  153. for i in 0..<pageCount {
  154. let page = pdfListView.document?.page(at: i)
  155. page?.removeAllAnnotations()
  156. }
  157. self.pdfViewController?.pdfListView?.setNeedsDisplayForVisiblePages()
  158. self.pdfViewController?.pdfListView?.updateActiveAnnotations([])
  159. completionHandler(true)
  160. } else {
  161. completionHandler(false)
  162. }
  163. }
  164. func importAnnotations(xfdfFile : URL, completionHandler: @escaping (Bool) -> Void) {
  165. if let pdfListView = self.pdfViewController?.pdfListView {
  166. let documentFolder = NSHomeDirectory().appending("/Documents/Files")
  167. if !FileManager.default.fileExists(atPath: documentFolder) {
  168. try? FileManager.default.createDirectory(at: URL(fileURLWithPath: documentFolder), withIntermediateDirectories: true, attributes: nil)
  169. }
  170. let documentPath = documentFolder + "/\(xfdfFile.lastPathComponent)"
  171. try? FileManager.default.copyItem(atPath: xfdfFile.path, toPath: documentPath)
  172. if !FileManager.default.fileExists(atPath: documentPath) {
  173. print("fail")
  174. }
  175. let success = pdfListView.document?.importAnnotation(fromXFDFPath: documentPath) ?? false
  176. if success {
  177. self.pdfViewController?.pdfListView?.setNeedsDisplayForVisiblePages()
  178. }
  179. completionHandler(success)
  180. } else {
  181. completionHandler(false)
  182. }
  183. }
  184. func exportAnnotations(completionHandler: @escaping (String) -> Void) {
  185. if let pdfListView = self.pdfViewController?.pdfListView {
  186. let fileNameWithExtension = pdfListView.document?.documentURL.lastPathComponent ?? ""
  187. let fileName = (fileNameWithExtension as NSString).deletingPathExtension
  188. let documentFolder = NSHomeDirectory().appending("/Documents/\(fileName)_xfdf.xfdf")
  189. let succes = pdfListView.document?.exportAnnotation(toXFDFPath: documentFolder) ?? false
  190. if succes {
  191. completionHandler(documentFolder)
  192. } else {
  193. completionHandler("")
  194. }
  195. } else {
  196. completionHandler("")
  197. }
  198. }
  199. func setDisplayPageIndex(pageIndex : Int) {
  200. if let pdfListView = self.pdfViewController?.pdfListView {
  201. pdfListView.go(toPageIndex: pageIndex, animated: false)
  202. }
  203. }
  204. func getCurrentPageIndex(completionHandler: @escaping (Int) -> Void) {
  205. if let pdfListView = self.pdfViewController?.pdfListView {
  206. completionHandler(pdfListView.currentPageIndex)
  207. } else {
  208. completionHandler(0)
  209. }
  210. }
  211. func hasChange(completionHandler: @escaping (Bool) -> Void) {
  212. if let pdfListView = self.pdfViewController?.pdfListView {
  213. let success = pdfListView.document?.isModified() ?? false
  214. completionHandler(success)
  215. } else {
  216. completionHandler(false)
  217. }
  218. }
  219. func setScale(scale : NSNumber){
  220. if let pdfListView = self.pdfViewController?.pdfListView {
  221. pdfListView.setScaleFactor(CGFloat(truncating: scale), animated: true)
  222. }
  223. }
  224. func getScale(completionHandler: @escaping (NSNumber) -> Void) {
  225. if let pdfListView = self.pdfViewController?.pdfListView {
  226. completionHandler(NSNumber(value: pdfListView.scaleFactor))
  227. } else {
  228. completionHandler(1.0)
  229. }
  230. }
  231. func setReadBackgroundColor(displayMode : NSString) {
  232. if let pdfListView = self.pdfViewController?.pdfListView {
  233. switch displayMode {
  234. case "light":
  235. pdfListView.displayMode = .normal
  236. case "dark":
  237. pdfListView.displayMode = .night
  238. case "sepia":
  239. pdfListView.displayMode = .soft
  240. case "reseda":
  241. pdfListView.displayMode = .green
  242. default:
  243. pdfListView.displayMode = .normal
  244. }
  245. pdfListView.layoutDocumentView()
  246. }
  247. }
  248. func getReadbackgroundColor(completionHandler: @escaping (NSString) -> Void) {
  249. if let pdfListView = self.pdfViewController?.pdfListView {
  250. let dispalyMode = pdfListView.displayMode
  251. switch dispalyMode {
  252. case .normal:
  253. completionHandler("#FFFFFF")
  254. case .night:
  255. completionHandler("#000000")
  256. case .soft:
  257. completionHandler("#FFFFFF")
  258. case .green:
  259. completionHandler("#FFEFBE")
  260. case .custom:
  261. completionHandler("#CDE6D0")
  262. @unknown default:
  263. completionHandler("#FFFFFF")
  264. }
  265. } else {
  266. completionHandler("#FFFFFF")
  267. }
  268. }
  269. func setFormFieldHighlight(formFieldHighlight : Bool){
  270. if let pdfListView = self.pdfViewController?.pdfListView {
  271. CPDFKitConfig.sharedInstance().setEnableFormFieldHighlight(formFieldHighlight)
  272. pdfListView.layoutDocumentView()
  273. }
  274. }
  275. func isFormFieldHighlight(completionHandler: @escaping (Bool) -> Void){
  276. completionHandler(CPDFKitConfig.sharedInstance().enableFormFieldHighlight())
  277. }
  278. func setLinkHighlight(linkHighlight : Bool) {
  279. if let pdfListView = self.pdfViewController?.pdfListView {
  280. CPDFKitConfig.sharedInstance().setEnableLinkFieldHighlight(linkHighlight)
  281. pdfListView.layoutDocumentView()
  282. }
  283. }
  284. func isLinkHighlight(completionHandler: @escaping (Bool) -> Void){
  285. completionHandler(CPDFKitConfig.sharedInstance().enableLinkFieldHighlight())
  286. }
  287. func setVerticalMode(isVerticalMode : Bool) {
  288. if let pdfListView = self.pdfViewController?.pdfListView {
  289. pdfListView.displayDirection = isVerticalMode ? .vertical : .horizontal
  290. pdfListView.layoutDocumentView()
  291. }
  292. }
  293. func isVerticalMode(completionHandler: @escaping (Bool) -> Void){
  294. if let pdfListView = self.pdfViewController?.pdfListView {
  295. completionHandler(pdfListView.displayDirection == .vertical)
  296. } else {
  297. completionHandler(true)
  298. }
  299. }
  300. func setContinueMode(isContinueMode : Bool) {
  301. if let pdfListView = self.pdfViewController?.pdfListView {
  302. pdfListView.displaysPageBreaks = isContinueMode
  303. pdfListView.layoutDocumentView()
  304. }
  305. }
  306. func isContinueMode(completionHandler: @escaping (Bool) -> Void){
  307. if let pdfListView = self.pdfViewController?.pdfListView {
  308. completionHandler(pdfListView.displaysPageBreaks)
  309. }else {
  310. completionHandler(true)
  311. }
  312. }
  313. func setDoublePageMode(isDoublePageMode : Bool) {
  314. if let pdfListView = self.pdfViewController?.pdfListView {
  315. pdfListView.displayTwoUp = isDoublePageMode
  316. pdfListView.displaysAsBook = false
  317. pdfListView.layoutDocumentView()
  318. }
  319. }
  320. func isDoublePageMode(completionHandler: @escaping (Bool) -> Void){
  321. if let pdfListView = self.pdfViewController?.pdfListView {
  322. completionHandler(pdfListView.displayTwoUp)
  323. }else {
  324. completionHandler(true)
  325. }
  326. }
  327. func setCoverPageMode(isCoverPageMode : Bool) {
  328. if let pdfListView = self.pdfViewController?.pdfListView {
  329. pdfListView.displayTwoUp = isCoverPageMode
  330. pdfListView.displaysAsBook = isCoverPageMode
  331. pdfListView.layoutDocumentView()
  332. }
  333. }
  334. func isCoverPageMode(completionHandler: @escaping (Bool) -> Void){
  335. if let pdfListView = self.pdfViewController?.pdfListView {
  336. completionHandler(pdfListView.displaysAsBook)
  337. }else {
  338. completionHandler(true)
  339. }
  340. }
  341. func setCropMode(isCropMode : Bool) {
  342. if let pdfListView = self.pdfViewController?.pdfListView {
  343. pdfListView.displayCrop = isCropMode
  344. pdfListView.layoutDocumentView()
  345. }
  346. }
  347. func isCropMode(completionHandler: @escaping (Bool) -> Void){
  348. if let pdfListView = self.pdfViewController?.pdfListView {
  349. completionHandler(pdfListView.displayCrop)
  350. }else {
  351. completionHandler(true)
  352. }
  353. }
  354. func setPreviewMode(viewMode : String) {
  355. switch viewMode {
  356. case "viewer":
  357. self.pdfViewController?.enterViewerMode()
  358. case "annotations":
  359. self.pdfViewController?.enterAnnotationMode()
  360. case "contentEditor":
  361. self.pdfViewController?.enterEditMode()
  362. case "forms":
  363. self.pdfViewController?.enterFormMode()
  364. case "signatures":
  365. self.pdfViewController?.enterSignatureMode()
  366. default:
  367. self.pdfViewController?.enterViewerMode()
  368. }
  369. }
  370. func getPreviewMode(completionHandler: @escaping (String) -> Void) {
  371. let state = self.pdfViewController?.functionTypeState ?? .viewer
  372. switch state {
  373. case .viewer:
  374. completionHandler("viewer")
  375. case .edit:
  376. completionHandler("contentEditor")
  377. case .annotation:
  378. completionHandler("annotations")
  379. case .form:
  380. completionHandler("forms")
  381. case .signature:
  382. completionHandler("signatures")
  383. default:
  384. completionHandler("viewer")
  385. }
  386. }
  387. func showThumbnailView(isEditMode : Bool) {
  388. if isEditMode {
  389. self.pdfViewController?.enterPDFPageEdit()
  390. } else {
  391. self.pdfViewController?.enterThumbnail()
  392. }
  393. }
  394. func showBotaView() {
  395. self.pdfViewController?.buttonItemClicked_Bota(UIButton(frame: .zero))
  396. }
  397. func showAddWatermarkView(saveAsNewFile : Bool) {
  398. self.pdfViewController?.enterPDFWatermark(isSaveAs: saveAsNewFile)
  399. }
  400. func showSecurityView() {
  401. self.pdfViewController?.enterPDFSecurity()
  402. }
  403. func showDisplaySettingView() {
  404. self.pdfViewController?.enterPDFSetting()
  405. }
  406. func enterSnipMode() {
  407. self.pdfViewController?.enterPDFSnipImageMode()
  408. }
  409. func exitSnipMode() {
  410. self.pdfViewController?.exitPDFSnipImageMode()
  411. }
  412. func open(document : URL, password : String, completionHandler: @escaping (Bool) -> Void) {
  413. if let pdfListView = self.pdfViewController?.pdfListView {
  414. let newDocument = CPDFDocument(url: document)
  415. if(newDocument?.isLocked == true){
  416. newDocument?.unlock(withPassword: password)
  417. }
  418. pdfListView.document = newDocument
  419. self.pdfViewController?.filePath = newDocument?.documentURL.path
  420. pdfListView.setNeedsDisplay()
  421. completionHandler(true)
  422. if newDocument?.isImageDocument() == true {
  423. let okAction = UIAlertAction(title: NSLocalizedString("OK", comment: ""), style: .default) { _ in
  424. self.navigationController?.popViewController(animated: true)
  425. }
  426. let alert = UIAlertController(title: NSLocalizedString("Warning", comment: ""), message: NSLocalizedString("The current page is scanned images that do not support adding highlights, underlines, strikeouts, and squiggly lines.", comment: ""), preferredStyle: .alert)
  427. alert.addAction(okAction)
  428. UIApplication.presentedViewController()?.present(alert, animated: true, completion: nil)
  429. }
  430. } else {
  431. completionHandler(false)
  432. }
  433. }
  434. func getFileName(completionHandler: @escaping (String) -> Void){
  435. if let pdfListView = self.pdfViewController?.pdfListView {
  436. completionHandler(pdfListView.document.documentURL.lastPathComponent)
  437. }else {
  438. completionHandler("")
  439. }
  440. }
  441. func isEncrypted(completionHandler: @escaping (Bool) -> Void){
  442. if let pdfListView = self.pdfViewController?.pdfListView {
  443. completionHandler(pdfListView.document.isEncrypted)
  444. }else {
  445. completionHandler(false)
  446. }
  447. }
  448. func isImageDoc(completionHandler: @escaping (Bool) -> Void){
  449. if let pdfListView = self.pdfViewController?.pdfListView {
  450. completionHandler(pdfListView.document.isImageDocument())
  451. }else {
  452. completionHandler(false)
  453. }
  454. }
  455. func getPermissions(completionHandler: @escaping (NSNumber) -> Void) {
  456. if let pdfListView = self.pdfViewController?.pdfListView {
  457. let permissions = pdfListView.document?.permissionsStatus ?? .none
  458. switch permissions {
  459. case .none:
  460. completionHandler(0)
  461. case .user:
  462. completionHandler(1)
  463. case .owner:
  464. completionHandler(2)
  465. default:
  466. completionHandler(0)
  467. }
  468. }else {
  469. completionHandler(0)
  470. }
  471. }
  472. func getPageCount(completionHandler: @escaping (NSNumber) -> Void) {
  473. if let pdfListView = self.pdfViewController?.pdfListView {
  474. completionHandler(pdfListView.document.pageCount as NSNumber)
  475. }else {
  476. completionHandler(0)
  477. }
  478. }
  479. func checkOwnerUnlocked(completionHandler: @escaping (Bool) -> Void) {
  480. if let pdfListView = self.pdfViewController?.pdfListView {
  481. completionHandler(pdfListView.document.isCheckOwnerUnlocked())
  482. }else {
  483. completionHandler(false)
  484. }
  485. }
  486. func checkOwnerPassword(password : String, completionHandler: @escaping (Bool) -> Void) {
  487. if let pdfListView = self.pdfViewController?.pdfListView {
  488. completionHandler(pdfListView.document.checkOwnerPassword(password))
  489. }else {
  490. completionHandler(false)
  491. }
  492. }
  493. func removePassword(completionHandler: @escaping (Bool) -> Void) {
  494. if let pdfListView = self.pdfViewController?.pdfListView {
  495. let newDocument = pdfListView.document
  496. let url = newDocument?.documentURL
  497. let success = newDocument?.writeDecrypt(to: url, isSaveFontSubset: true) ?? false
  498. completionHandler(success)
  499. } else {
  500. completionHandler(false)
  501. }
  502. }
  503. func setPassword(info : NSDictionary, completionHandler: @escaping (Bool) -> Void) {
  504. if let pdfListView = self.pdfViewController?.pdfListView {
  505. let _info = info as? [String: Any]
  506. let userPassword : String = self.getValue(from: _info, key: "user_password", defaultValue: "")
  507. let ownerPassword : String = self.getValue(from: _info, key: "owner_password", defaultValue: "")
  508. let allowsPrinting : Bool = self.getValue(from: _info, key: "allows_printing", defaultValue: true)
  509. let allowsCopying : Bool = self.getValue(from: _info, key: "allows_copying", defaultValue: true)
  510. let encryptAlgo : String = self.getValue(from: _info, key: "encrypt_algo", defaultValue: "rc4")
  511. var level: Int = 0
  512. // Encryption mode, the type passed in is:rc4, aes128, aes256, noEncryptAlgo
  513. switch encryptAlgo {
  514. case "rc4":
  515. level = 0
  516. case "aes128":
  517. level = 1
  518. case "aes256":
  519. level = 2
  520. case "noEncryptAlgo":
  521. level = 3
  522. default:
  523. level = 3
  524. }
  525. var options:[CPDFDocumentWriteOption: Any] = [:]
  526. options[CPDFDocumentWriteOption.userPasswordOption] = userPassword
  527. options[CPDFDocumentWriteOption.ownerPasswordOption] = ownerPassword
  528. options[CPDFDocumentWriteOption.allowsPrintingOption] = allowsPrinting
  529. options[CPDFDocumentWriteOption.allowsCopyingOption] = allowsCopying
  530. options[CPDFDocumentWriteOption.encryptionLevelOption] = NSNumber(value: level)
  531. let newDocument = pdfListView.document
  532. let url = newDocument?.documentURL
  533. let success = newDocument?.write(to: url, withOptions: options, isSaveFontSubset: true) ?? false
  534. completionHandler(success)
  535. } else {
  536. completionHandler(false)
  537. }
  538. }
  539. func getEncryptAlgo(completionHandler: @escaping (String) -> Void) {
  540. if let pdfListView = self.pdfViewController?.pdfListView {
  541. let encryptAlgo = pdfListView.document.encryptionLevel
  542. switch encryptAlgo {
  543. case .RC4:
  544. completionHandler("rc4")
  545. case .AES128:
  546. completionHandler("aes128")
  547. case .AES256:
  548. completionHandler("aes256")
  549. case .noEncryptAlgo:
  550. completionHandler("noEncryptAlgo")
  551. default:
  552. completionHandler("noEncryptAlgo")
  553. }
  554. }else {
  555. completionHandler("noEncryptAlgo")
  556. }
  557. }
  558. func printDocument() {
  559. self.pdfViewController?.enterPrintState();
  560. }
  561. func importWidgets(xfdfFile : URL, completionHandler: @escaping (Bool) -> Void) {
  562. if let pdfListView = self.pdfViewController?.pdfListView {
  563. let documentFolder = NSHomeDirectory().appending("/Documents/Files")
  564. if !FileManager.default.fileExists(atPath: documentFolder) {
  565. try? FileManager.default.createDirectory(at: URL(fileURLWithPath: documentFolder), withIntermediateDirectories: true, attributes: nil)
  566. }
  567. let documentPath = documentFolder + "/\(xfdfFile.lastPathComponent)"
  568. try? FileManager.default.copyItem(atPath: xfdfFile.path, toPath: documentPath)
  569. if !FileManager.default.fileExists(atPath: documentPath) {
  570. print("fail")
  571. }
  572. let success = pdfListView.document?.importForm(fromXFDFPath: documentPath) ?? false
  573. if success {
  574. self.pdfViewController?.pdfListView?.setNeedsDisplayForVisiblePages()
  575. }
  576. completionHandler(success)
  577. } else {
  578. completionHandler(false)
  579. }
  580. }
  581. func getDocumentPath(completionHandler: @escaping (String) -> Void) {
  582. if let pdfListView = self.pdfViewController?.pdfListView {
  583. let documentPath = pdfListView.document.documentURL.path
  584. completionHandler(documentPath)
  585. }
  586. }
  587. func exportWidgets(completionHandler: @escaping (String) -> Void) {
  588. if let pdfListView = self.pdfViewController?.pdfListView {
  589. let fileNameWithExtension = pdfListView.document?.documentURL.lastPathComponent ?? ""
  590. let fileName = (fileNameWithExtension as NSString).deletingPathExtension
  591. let documentFolder = NSHomeDirectory().appending("/Documents/\(fileName)_xfdf.xfdf")
  592. let succes = pdfListView.document?.export(toXFDFPath: documentFolder) ?? false
  593. if succes {
  594. completionHandler(documentFolder)
  595. } else {
  596. completionHandler("")
  597. }
  598. } else {
  599. completionHandler("")
  600. }
  601. }
  602. func flattenAllPages(savePath: URL, fontSubset: Bool, completionHandler: @escaping (Bool) -> Void) {
  603. if let pdfListView = self.pdfViewController?.pdfListView {
  604. let success = pdfListView.document.writeFlatten(to: savePath, isSaveFontSubset: fontSubset)
  605. completionHandler(success)
  606. } else {
  607. completionHandler(false)
  608. }
  609. }
  610. func saveAs(savePath: URL, removeSecurity: Bool, fontSubset: Bool, completionHandler: @escaping (Bool) -> Void) {
  611. if let pdfListView = self.pdfViewController?.pdfListView {
  612. var success: Bool = false
  613. if removeSecurity {
  614. success = pdfListView.document.writeDecrypt(to: savePath, isSaveFontSubset: fontSubset)
  615. } else {
  616. success = pdfListView.document.write(to: savePath, isSaveFontSubset: fontSubset)
  617. }
  618. completionHandler(success)
  619. } else {
  620. completionHandler(false)
  621. }
  622. }
  623. func importDocument(_ filePath:URL, _ info : NSDictionary, completionHandler: @escaping (Bool) -> Void) {
  624. if let pdfListView = self.pdfViewController?.pdfListView {
  625. let _info = info as? [String: Any]
  626. let password: String = self.getValue(from: _info, key: "password", defaultValue: "")
  627. let pages: [Int] = self.getValue(from: _info, key: "pages", defaultValue: [])
  628. let insert_position: Int = self.getValue(from: _info, key: "insert_position", defaultValue: 0)
  629. let _document = CPDFDocument(url: filePath)
  630. if _document?.isLocked == true {
  631. _document?.unlock(withPassword: password)
  632. }
  633. let success = self.insertPDFDocument(_document!, Pages: pages, Position: UInt(insert_position))
  634. completionHandler(success)
  635. } else {
  636. completionHandler(false)
  637. }
  638. }
  639. func splitDocumentPages(savePath: URL, pages: [Int], completionHandler: @escaping (Bool) -> Void) {
  640. if let pdfListView = self.pdfViewController?.pdfListView {
  641. let success = self.extractPDFDocument(savePath, Pages: pages)
  642. completionHandler(success)
  643. } else {
  644. completionHandler(false)
  645. }
  646. }
  647. // MARK: - CPDFViewBaseControllerDelete
  648. func PDFViewBaseController(_ baseController: CPDFViewBaseController, SaveState success: Bool) {
  649. self.delegate?.saveDocumentChange(self)
  650. }
  651. func PDFViewBaseController(_ baseController: CPDFViewBaseController, currentPageIndex index: Int) {
  652. self.delegate?.onPageChanged(self, pageIndex: index)
  653. }
  654. // MARK: - RCT Methods
  655. private var configuration: String = ""
  656. @objc func setConfiguration(_ newSection: String) {
  657. configuration = newSection
  658. if (document.path.count > 1) && (configuration.count > 1) {
  659. createCPDFView()
  660. }
  661. }
  662. private var document: URL = URL(fileURLWithPath: "")
  663. @objc func setDocument(_ newSection: URL) {
  664. document = newSection
  665. if (document.path.count > 1) && (configuration.count > 1) {
  666. createCPDFView()
  667. }
  668. }
  669. private var password: String = ""
  670. @objc func setPassword(_ newSection: String) {
  671. password = newSection
  672. }
  673. public var onChange: RCTBubblingEventBlock?
  674. @objc func setOnChange(_ newSection: @escaping RCTBubblingEventBlock) {
  675. onChange = newSection
  676. }
  677. }