ComPDFKitRN.swift 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  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 documentHome = homeDiectory.appending("/Documents")
  130. if documentPath.hasPrefix(homeDiectory) && documentPath.hasPrefix(documentHome) {
  131. } else {
  132. let fileManager = FileManager.default
  133. let samplesFilePath = NSHomeDirectory().appending("/Documents/Files")
  134. let fileName = document.lastPathComponent
  135. let docsFilePath = samplesFilePath + "/" + fileName
  136. if !fileManager.fileExists(atPath: samplesFilePath) {
  137. try? FileManager.default.createDirectory(atPath: samplesFilePath, withIntermediateDirectories: true, attributes: nil)
  138. }
  139. try? FileManager.default.copyItem(atPath: document.path, toPath: docsFilePath)
  140. documentPath = docsFilePath
  141. }
  142. } else {
  143. success = document.startAccessingSecurityScopedResource()
  144. }
  145. let rootNav = ComPDFKit.presentedViewController()
  146. let jsonDataParse = CPDFJSONDataParse(String: configurationJson)
  147. guard let configuration = jsonDataParse.configuration else { return }
  148. self.pdfViewController = CPDFViewController(filePath: documentPath, password: password, configuration: configuration)
  149. self.pdfViewController?.delegate = self
  150. let nav = CNavigationController(rootViewController: self.pdfViewController!)
  151. nav.modalPresentationStyle = .fullScreen
  152. rootNav?.present(nav, animated: true)
  153. if success {
  154. document.stopAccessingSecurityScopedResource()
  155. }
  156. }
  157. }
  158. @objc(removeSignFileList:withRejecter:)
  159. func removeSignFileList(resolve: @escaping RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) {
  160. DispatchQueue.main.async {
  161. CSignatureManager.sharedManager.removeAllSignatures()
  162. resolve(true)
  163. }
  164. }
  165. @objc(pickFile:withRejecter:)
  166. func pickFile(resolve: @escaping RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) {
  167. DispatchQueue.main.async {
  168. let documentTypes = ["com.adobe.pdf"]
  169. let documentPickerViewController = UIDocumentPickerViewController(documentTypes: documentTypes, in: .open)
  170. documentPickerViewController.delegate = self
  171. UIApplication.presentedViewController()?.present(documentPickerViewController, animated: true, completion: nil)
  172. self._resolve = resolve
  173. }
  174. }
  175. @objc(setImportFontDir:addSysFont:withResolver: withRejecter:)
  176. func setImportFontDir(fontDir : String, addSysFont : Bool, resolve: @escaping RCTPromiseResolveBlock, reject: @escaping RCTPromiseRejectBlock) {
  177. let fileManager = FileManager.default
  178. let documentDirectory = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first!
  179. let destinationPath = documentDirectory.appendingPathComponent("Font")
  180. do {
  181. if fileManager.fileExists(atPath: destinationPath.path) {
  182. try fileManager.removeItem(at: destinationPath)
  183. }
  184. try fileManager.copyItem(atPath: fontDir, toPath: destinationPath.path)
  185. CPDFFont.setImportDir(destinationPath.path, isContainSysFont: addSysFont)
  186. } catch {
  187. print("Error copying Font directory: \(error)")
  188. }
  189. resolve(true)
  190. }
  191. //MARK: - ViewController Method
  192. /**
  193. * CPDFViewBaseControllerDelete delegate to dismiss ViewController.<br/>
  194. */
  195. func PDFViewBaseControllerDissmiss(_ baseControllerDelete: CPDFViewBaseController) {
  196. baseControllerDelete.dismiss(animated: true)
  197. }
  198. func PDFViewBaseController(_ baseController: CPDFViewBaseController, SaveState success: Bool) {
  199. }
  200. /**
  201. * Cet a root ViewController.<br/>
  202. */
  203. class func presentedViewController() -> UIViewController? {
  204. var rootViewController: UIViewController? = nil
  205. if let appDelegate = UIApplication.shared.delegate as? NSObject {
  206. if appDelegate.responds(to: Selector(("viewController"))) {
  207. rootViewController = appDelegate.value(forKey: "viewController") as? UIViewController
  208. }
  209. }
  210. if rootViewController == nil, let appDelegate = UIApplication.shared.delegate as? NSObject, appDelegate.responds(to: #selector(getter: UIApplicationDelegate.window)) {
  211. if let window = appDelegate.value(forKey: "window") as? UIWindow {
  212. rootViewController = window.rootViewController
  213. }
  214. }
  215. if rootViewController == nil {
  216. if let window = UIApplication.shared.keyWindow {
  217. rootViewController = window.rootViewController
  218. }
  219. }
  220. guard let finalRootViewController = rootViewController else {
  221. return nil
  222. }
  223. var currentViewController = finalRootViewController
  224. while let presentedViewController = currentViewController.presentedViewController {
  225. if !(presentedViewController is UIAlertController) && currentViewController.modalPresentationStyle != .popover {
  226. currentViewController = presentedViewController
  227. } else {
  228. return currentViewController
  229. }
  230. }
  231. return currentViewController
  232. }
  233. //MARK: - UIDocumentPickerDelegate
  234. func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
  235. let fileUrlAuthozied = urls.first?.startAccessingSecurityScopedResource() ?? false
  236. if fileUrlAuthozied {
  237. let filePath = urls.first?.path ?? ""
  238. self._resolve?(filePath)
  239. }
  240. }
  241. }