ComPDFKitRN.swift 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  1. // Copyright © 2014-2025 PDF Technologies, Inc. All Rights Reserved.
  2. //
  3. // THIS SOURCE CODE AND ANY ACCOMPANYING DOCUMENTATION ARE PROTECTED BY INTERNATIONAL COPYRIGHT LAW
  4. // AND MAY NOT BE RESOLD OR REDISTRIBUTED. USAGE IS BOUND TO THE ComPDFKit LICENSE AGREEMENT.
  5. // UNAUTHORIZED REPRODUCTION OR DISTRIBUTION IS SUBJECT TO CIVIL AND CRIMINAL PENALTIES.
  6. // This notice may not be removed from this file.
  7. //
  8. import UIKit
  9. import Foundation
  10. import ComPDFKit
  11. import ComPDFKit_Tools
  12. /**
  13. * RN and iOS native ComPDFKit SDK interaction class
  14. *
  15. */
  16. @objc(ComPDFKit)
  17. class ComPDFKit: NSObject, CPDFViewBaseControllerDelete, UIDocumentPickerDelegate{
  18. private var pdfViewController: CPDFViewController?
  19. private var _resolve: RCTPromiseResolveBlock?
  20. /**
  21. * Get the version number of the ComPDFKit SDK.<br/>
  22. * For example: "2.0.0".<br/>
  23. * <p></p>
  24. * Usage example:<br/><br/>
  25. * <pre>
  26. * ComPDFKit.getVersionCode().then((versionCode : string) => {
  27. * console.log('ComPDFKit SDK Version:', versionCode)
  28. * })
  29. * </pre>
  30. *
  31. */
  32. @objc(getVersionCode:withRejecter:)
  33. func getVersionCode(resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) -> Void {
  34. resolve(String(CPDFKit.sharedInstance().versionNumber))
  35. }
  36. /**
  37. * Get the build tag of the ComPDFKit PDF SDK.<br/>
  38. * For example: "build_beta_2.0.0_42db96987_202404081007"<br/>
  39. * <p></p>
  40. *
  41. * Usage example:<br/>
  42. * <pre>
  43. * ComPDFKit.getSDKBuildTag().then((buildTag : string) => {
  44. * console.log('ComPDFKit Build Tag:', buildTag)
  45. * })
  46. * </pre>
  47. *
  48. */
  49. @objc(getSDKBuildTag:withRejecter:)
  50. func getSDKBuildTag(resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) -> Void {
  51. let sdkBuildTag = CPDFKit.sharedInstance().versionString
  52. resolve(sdkBuildTag)
  53. }
  54. /**
  55. * Initialize the ComPDFKit PDF SDK using offline authentication.<br/>
  56. * <p></p>
  57. * Usage example:<br/>
  58. * <pre>
  59. * ComPDFKit.init_('license')
  60. * </pre>
  61. *
  62. * @param license The offline license.
  63. */
  64. @objc(init_: withResolver: withRejecter:)
  65. func init_(license : String,resolve: @escaping RCTPromiseResolveBlock, reject: @escaping RCTPromiseRejectBlock){
  66. DispatchQueue.main.async {
  67. let code = CPDFKit.verify(withKey: license)
  68. print("ComPDFKitRN-iOS init_:\(code)")
  69. resolve(code == CPDFKitLicenseCode.success)
  70. }
  71. }
  72. /**
  73. * Initialize the ComPDFKit PDF SDK using online authentication. <br/>
  74. * Requires internet connection. Please ensure that the network permission has been added in [AndroidManifest.xml] file. <br/>
  75. * {@link iOS.Manifest.permission#INTERNET} <br/>
  76. * <p></p>
  77. * Usage example:
  78. * <pre>
  79. * ComPDFKit.initialize(androidLicense, iosLicense)
  80. * </pre>
  81. *
  82. * @param androidOnlineLicense The online license for the ComPDFKit SDK on Android platform.
  83. * @param iosOnlineLicense The online license for the ComPDFKit SDK on iOS platform.
  84. */
  85. @objc(initialize: iosOnlineLicense: withResolver: withRejecter:)
  86. func initialize(_ androidOnlineLicense: String, iosOnlineLicense: String, resolve: @escaping RCTPromiseResolveBlock, reject: @escaping RCTPromiseRejectBlock) {
  87. DispatchQueue.main.async {
  88. CPDFKit.verify(withOnlineLicense: iosOnlineLicense) { code, message in
  89. print("ComPDFKitRN-iOS initialize: \(code), Message:\(String(describing: message))")
  90. resolve(code == CPDFKitOnlineLicenseCode.success)
  91. }
  92. }
  93. }
  94. /**
  95. * Display a PDF.<br/>
  96. *
  97. * Usage example:<br/>
  98. * <pre>
  99. * ComPDFKit.openDocument(document, password, configurationJson)
  100. * </pre>
  101. *
  102. * (iOS) For local storage file path: <br/>
  103. * <pre>
  104. * document = "file:///storage/emulated/0/Download/sample.pdf";<br/>
  105. * </pre>
  106. *
  107. * (iOS) For content Uri: <br/>
  108. * <pre>
  109. * document = "content://...";
  110. * </pre>
  111. *
  112. * (iOS) For assets path: <br/>
  113. * <pre>
  114. * document = "file:///android_asset/..."
  115. * </pre>
  116. *
  117. * @param document The document URI or file path.
  118. * @param password The document password.
  119. * @param configurationJson Configuration data in JSON format.
  120. */
  121. @objc(openDocument: password: configurationJson:)
  122. func openDocument(document : URL, password: String, configurationJson : String) -> Void {
  123. DispatchQueue.main.async {
  124. var documentPath = document.path
  125. var success = false
  126. let homeDiectory = NSHomeDirectory()
  127. let bundlePath = Bundle.main.bundlePath
  128. if (documentPath.hasPrefix(homeDiectory) || documentPath.hasPrefix(bundlePath)) {
  129. let fileManager = FileManager.default
  130. let samplesFilePath = NSHomeDirectory().appending("/Documents/Files")
  131. let fileName = document.lastPathComponent
  132. let docsFilePath = samplesFilePath + "/" + fileName
  133. if !fileManager.fileExists(atPath: samplesFilePath) {
  134. try? FileManager.default.createDirectory(atPath: samplesFilePath, withIntermediateDirectories: true, attributes: nil)
  135. }
  136. try? FileManager.default.copyItem(atPath: document.path, toPath: docsFilePath)
  137. documentPath = docsFilePath
  138. } else {
  139. success = document.startAccessingSecurityScopedResource()
  140. }
  141. let rootNav = ComPDFKit.presentedViewController()
  142. let jsonDataParse = CPDFJSONDataParse(String: configurationJson)
  143. guard let configuration = jsonDataParse.configuration else { return }
  144. self.pdfViewController = CPDFViewController(filePath: documentPath, password: password, configuration: configuration)
  145. self.pdfViewController?.delegate = self
  146. let nav = CNavigationController(rootViewController: self.pdfViewController!)
  147. nav.modalPresentationStyle = .fullScreen
  148. rootNav?.present(nav, animated: true)
  149. if success {
  150. document.stopAccessingSecurityScopedResource()
  151. }
  152. }
  153. }
  154. @objc(removeSignFileList:withRejecter:)
  155. func removeSignFileList(resolve: @escaping RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) {
  156. DispatchQueue.main.async {
  157. CSignatureManager.sharedManager.removeAllSignatures()
  158. resolve(true)
  159. }
  160. }
  161. @objc(pickFile:withRejecter:)
  162. func pickFile(resolve: @escaping RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) {
  163. DispatchQueue.main.async {
  164. let documentTypes = ["com.adobe.pdf"]
  165. let documentPickerViewController = UIDocumentPickerViewController(documentTypes: documentTypes, in: .open)
  166. documentPickerViewController.delegate = self
  167. UIApplication.presentedViewController()?.present(documentPickerViewController, animated: true, completion: nil)
  168. self._resolve = resolve
  169. }
  170. }
  171. @objc(setImportFontDir:addSysFont:withResolver: withRejecter:)
  172. func setImportFontDir(fontDir : String, addSysFont : Bool, resolve: @escaping RCTPromiseResolveBlock, reject: @escaping RCTPromiseRejectBlock) {
  173. let fileManager = FileManager.default
  174. let documentDirectory = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first!
  175. let destinationPath = documentDirectory.appendingPathComponent("Font")
  176. do {
  177. if fileManager.fileExists(atPath: destinationPath.path) {
  178. try fileManager.removeItem(at: destinationPath)
  179. }
  180. try fileManager.copyItem(atPath: fontDir, toPath: destinationPath.path)
  181. CPDFFont.setImportDir(destinationPath.path, isContainSysFont: addSysFont)
  182. } catch {
  183. print("Error copying Font directory: \(error)")
  184. }
  185. resolve(true)
  186. }
  187. //MARK: - ViewController Method
  188. /**
  189. * CPDFViewBaseControllerDelete delegate to dismiss ViewController.<br/>
  190. */
  191. func PDFViewBaseControllerDissmiss(_ baseControllerDelete: CPDFViewBaseController) {
  192. baseControllerDelete.dismiss(animated: true)
  193. }
  194. func PDFViewBaseController(_ baseController: CPDFViewBaseController, SaveState success: Bool) {
  195. }
  196. /**
  197. * Cet a root ViewController.<br/>
  198. */
  199. class func presentedViewController() -> UIViewController? {
  200. var rootViewController: UIViewController? = nil
  201. if let appDelegate = UIApplication.shared.delegate as? NSObject {
  202. if appDelegate.responds(to: Selector(("viewController"))) {
  203. rootViewController = appDelegate.value(forKey: "viewController") as? UIViewController
  204. }
  205. }
  206. if rootViewController == nil, let appDelegate = UIApplication.shared.delegate as? NSObject, appDelegate.responds(to: #selector(getter: UIApplicationDelegate.window)) {
  207. if let window = appDelegate.value(forKey: "window") as? UIWindow {
  208. rootViewController = window.rootViewController
  209. }
  210. }
  211. if rootViewController == nil {
  212. if let window = UIApplication.shared.keyWindow {
  213. rootViewController = window.rootViewController
  214. }
  215. }
  216. guard let finalRootViewController = rootViewController else {
  217. return nil
  218. }
  219. var currentViewController = finalRootViewController
  220. while let presentedViewController = currentViewController.presentedViewController {
  221. if !(presentedViewController is UIAlertController) && currentViewController.modalPresentationStyle != .popover {
  222. currentViewController = presentedViewController
  223. } else {
  224. return currentViewController
  225. }
  226. }
  227. return currentViewController
  228. }
  229. //MARK: - UIDocumentPickerDelegate
  230. func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
  231. let fileUrlAuthozied = urls.first?.startAccessingSecurityScopedResource() ?? false
  232. if fileUrlAuthozied {
  233. let filePath = urls.first?.path ?? ""
  234. self._resolve?(filePath)
  235. }
  236. }
  237. }