KMImageToPDFMethod.swift 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  1. //
  2. // KMImageToPDFMethod.swift
  3. // PDF Reader Pro
  4. //
  5. // Created by kdanmobile on 2023/10/26.
  6. //
  7. import Foundation
  8. let kImageToPDFFolderPath = kTempSavePath?.stringByAppendingPathComponent("ImageToPDF")
  9. @objc(KMImageToPDFMethod)
  10. protocol KMImageToPDFMethodDelegate: AnyObject {
  11. func imageToPDFMethod(_ method: KMImageToPDFMethod, progress: Float)
  12. }
  13. typealias ImageToPDFResultBlock = (_ savePath: String, _ errorArr: Array<Any>, _ errorOCRArray: Array<Any>) -> Void
  14. class KMImageToPDFMethod: NSObject, KMGOCRManagerDelegate {
  15. var imageTopdfDelegate: KMImageToPDFMethodDelegate?
  16. var password: String = ""
  17. var convertIndex: Int = 0
  18. var photoArray: Array<Any>?
  19. var errorArray: NSMutableArray!
  20. var isOCR = false
  21. var isCreatPDF = false
  22. var isMerge = false
  23. var isSaveAsText = false
  24. var saveAsTestPath = ""
  25. var results: NSMutableArray!
  26. var fileSavePath = ""
  27. var OCRResultString = ""
  28. var completeBlock: ImageToPDFResultBlock?
  29. var errorOCRArray: NSMutableArray!
  30. var appendPDF: CPDFDocument?
  31. override init() {
  32. super.init()
  33. if !FileManager.default.fileExists(atPath: kImageToPDFFolderPath ?? "") {
  34. try? FileManager.default.createDirectory(at: URL(fileURLWithPath: kImageToPDFFolderPath ?? "") , withIntermediateDirectories: false, attributes: nil)
  35. }
  36. self.errorArray = NSMutableArray()
  37. self.results = NSMutableArray()
  38. self.errorOCRArray = NSMutableArray()
  39. }
  40. deinit {
  41. NotificationCenter.default.removeObserver(self)
  42. imageTopdfDelegate = nil
  43. }
  44. func exportPDFFile(fileArray: Array<Any>, savePath: String, isOCR: Bool, isCreatPDF: Bool, isMerge: Bool, isSaveAsText: Bool, complete: @escaping ImageToPDFResultBlock) {
  45. self.convertIndex = 0
  46. self.photoArray = fileArray
  47. self.isOCR = isOCR
  48. self.isCreatPDF = isCreatPDF
  49. self.isMerge = isMerge
  50. self.isSaveAsText = isSaveAsText
  51. self.fileSavePath = savePath
  52. self.completeBlock = complete
  53. self.OCRResultString = ""
  54. self.errorArray.removeAllObjects()
  55. self.errorOCRArray.removeAllObjects()
  56. if !isCreatPDF {
  57. appendPDF = CPDFDocument(url: URL(fileURLWithPath: savePath))
  58. if ((appendPDF?.unlock(withPassword:self.password)) != nil) {
  59. }
  60. }
  61. if isOCR {
  62. let languages = KMGOCRManager.default().selectedLanguages.value(forKeyPath: KMGOCRLanguageCodeKey) as! [Any]
  63. var images = [AnyObject]()
  64. for i in 0 ..< (photoArray?.count ?? 0) {
  65. let filePaht: String = photoArray?[i] as! String
  66. if filePaht.count > 0 && FileManager.default.fileExists(atPath: filePaht) {
  67. let image = NSImage(contentsOfFile: filePaht)
  68. images.append(image!)
  69. } else {
  70. self.errorArray.add(filePaht)
  71. }
  72. }
  73. if images.count < 1 {
  74. self.completeBlock?("", self.errorArray as! Array<Any>, self.errorOCRArray as! Array<Any>)
  75. return
  76. }
  77. let plan = UserDefaults.standard.integer(forKey: "KMOCRCurrentPlanKey")
  78. if plan == 0 {
  79. KMGOCRManager.default().ocrType = .google
  80. } else {
  81. KMGOCRManager.default().ocrType = .apple
  82. }
  83. KMGOCRManager.default().delegate = self
  84. KMGOCRManager.default().recognitionImages(images as! [NSImage], withLanguages: languages)
  85. } else {
  86. if isMerge {
  87. NotificationCenter.default.addObserver(self, selector: #selector(pdfDocumentPageWrite(notification:)), name: NSNotification.Name("PDFDocumentDidBeginPageWriteNotification"), object: nil)
  88. self.imageToPDFFile_MergeToOneFile(path: savePath, complete: complete)
  89. } else {
  90. self.imageToPDFFile_SeparateToFiles(path: savePath, complete: complete)
  91. }
  92. }
  93. }
  94. func imageToPDFFile_MergeToOneFile(path: String, complete: @escaping ImageToPDFResultBlock) {
  95. var pdf: CPDFDocument?
  96. var newPath: String = ""
  97. if self.isCreatPDF {
  98. pdf = CPDFDocument()
  99. newPath = path.stringByAppendingPathComponent("Untitled").stringByAppendingPathExtension("pdf")
  100. newPath = getUniqueFilePath(newPath)
  101. } else {
  102. newPath = path
  103. pdf = self.appendPDF
  104. }
  105. for pageCount in 0..<(photoArray?.count ?? 0) {
  106. var isDir: ObjCBool = false
  107. let filePath = photoArray?[pageCount] as! String
  108. if FileManager.default.fileExists(atPath: filePath, isDirectory: &isDir) && !isDir.boolValue {
  109. let image = NSImage(contentsOfFile: filePath)!
  110. _ = pdf?.km_insertPage(image.size, withImage: filePath, at: pdf?.pageCount ?? 0)
  111. }
  112. }
  113. var isSucceed = false
  114. if (pdf?.pageCount ?? 0) < 1 {
  115. } else {
  116. var options: [CPDFDocumentWriteOption : Any] = [:]
  117. if pdf!.isEncrypted {
  118. options.updateValue(password, forKey: .userPasswordOption)
  119. options.updateValue(password, forKey: .userPasswordOption)
  120. isSucceed = pdf?.write(toFile: newPath, withOptions: options) ?? false
  121. } else {
  122. isSucceed = pdf?.write(toFile: newPath) ?? false
  123. }
  124. }
  125. if !isSucceed {
  126. self.errorArray.add((newPath as NSString).lastPathComponent)
  127. }
  128. DispatchQueue.main.async {
  129. complete(newPath, self.errorArray as! Array<Any>, self.errorOCRArray as! Array<Any>)
  130. }
  131. }
  132. func imageToPDFFile_SeparateToFiles(path: String, complete: @escaping(ImageToPDFResultBlock)) {
  133. if convertIndex >= photoArray?.count ?? 0 {
  134. complete(path, Array<Any>(), errorOCRArray as! Array<Any>)
  135. return
  136. }
  137. let filePath: String = photoArray?[convertIndex] as! String
  138. let savePath = path
  139. var isDir: ObjCBool = false
  140. if FileManager.default.fileExists(atPath: filePath , isDirectory: &isDir) && !isDir.boolValue {
  141. let model = KMImageModel(filepath: filePath )
  142. let tString = model.photoName.deletingPathExtension.lastPathComponent//model.photoName.deletingPathExtension
  143. var newpath = path.stringByAppendingPathComponent(tString).stringByAppendingPathExtension("pdf")
  144. newpath = getUniqueFilePath(newpath)
  145. let pdf = CPDFDocument()
  146. if let imag = NSImage(contentsOfFile: filePath ) {
  147. _ = pdf?.km_insertPage(imag.size, withImage: filePath , at: pdf?.pageCount ?? 0)
  148. }
  149. // DispatchQueue.global().async {
  150. var isSucceed = false
  151. isSucceed = pdf?.write(toFile: newpath) ?? false
  152. var pre: Float = 0
  153. if self.photoArray?.count ?? 0 > 0{
  154. pre = Float(self.convertIndex + 1) / Float(self.photoArray?.count ?? 1)
  155. }else{
  156. pre = 0
  157. }
  158. if !isSucceed {
  159. self.errorArray.add(filePath)
  160. }
  161. if self.convertIndex < (self.photoArray?.count ?? 0) - 1 {
  162. self.convertIndex += 1
  163. self.imageToPDFFile_SeparateToFiles(path: savePath, complete: complete)
  164. DispatchQueue.main.async {
  165. self.imageTopdfDelegate?.imageToPDFMethod(self, progress: pre)
  166. }
  167. } else {
  168. DispatchQueue.main.async {
  169. complete(newpath, self.errorArray as! Array<Any>, self.errorOCRArray as! Array<Any>)
  170. }
  171. }
  172. // }
  173. } else {
  174. if convertIndex < (photoArray?.count ?? 0) - 1 {
  175. self.convertIndex += 1
  176. self.imageToPDFFile_SeparateToFiles(path: savePath, complete: complete)
  177. } else {
  178. DispatchQueue.main.async {
  179. complete(path, self.errorArray as! Array<Any>, self.errorOCRArray as! Array<Any>)
  180. }
  181. }
  182. }
  183. }
  184. func getUniqueFilePath(_ filePath: String) -> String {
  185. var i = 0
  186. var uniqueFilePath = filePath
  187. let fileManager = FileManager.default
  188. while fileManager.fileExists(atPath: uniqueFilePath) {
  189. i += 1
  190. let path = String(format: "%@(%d)", filePath.deletingPathExtension,i)
  191. uniqueFilePath = path.stringByAppendingPathExtension(filePath.pathExtension)
  192. }
  193. return uniqueFilePath
  194. }
  195. @objc func pdfDocumentPageWrite(notification: NSNotification) {
  196. if ((notification.userInfo?.isEmpty) != nil) { return }
  197. let num = notification.userInfo!["PDFDocumentPageIndex"] as! NSNumber
  198. let pdfDocument = notification.object as! CPDFDocument
  199. let pre = Float(num.intValue + 1) / (Float(pdfDocument.pageCount) * 1.0)
  200. DispatchQueue.main.async {
  201. self.imageTopdfDelegate?.imageToPDFMethod(self, progress: pre)
  202. }
  203. }
  204. //MARK: KMGOCRManagerDelegate
  205. func gocrManagerDidStartOCR(_ manager: KMGOCRManager!) {
  206. }
  207. func gocrManagerDidFinishOCR(_ manager: KMGOCRManager!) {
  208. }
  209. func gocrManager(_ manager: KMGOCRManager!, didCancelOCRImageAt index: Int) {
  210. }
  211. func gocrManager(_ manager: KMGOCRManager!, didStartOCRImageAt index: Int) {
  212. }
  213. func gocrManager(_ manager: KMGOCRManager!, didFinishOCRImageAt index: Int, results: [KMGOCRResult]!) {
  214. if (results != nil) {
  215. self.dealWithResults(results, OCRImageAtIndex: index)
  216. }
  217. }
  218. func gocrManager(_ manager: KMGOCRManager!, didFailureOCRImageAt index: Int, error: Error!) {
  219. let results = Array<KMGOCRResult>()
  220. self.errorOCRArray.add(self.photoArray?[index] as Any)
  221. self.dealWithResults(results, OCRImageAtIndex: index)
  222. }
  223. func dealWithResults(_ results: [KMGOCRResult]?, OCRImageAtIndex index: Int) {
  224. if isOCR {
  225. if isMerge {
  226. self.results.add(results as Any)
  227. var key = index
  228. if isCreatPDF {
  229. key = Int((self.appendPDF?.pageCount ?? 0) + UInt(index))
  230. }
  231. var contents = ""
  232. if OCRResultString.count > 0 {
  233. contents = self.OCRResultString
  234. }
  235. var str: String = ""
  236. if results!.count > 0 {
  237. guard let firstResult: KMGOCRResult = results?.first else {
  238. return
  239. }
  240. str = firstResult.text
  241. }
  242. contents = contents + "\n"
  243. contents = contents + "Page" + "\(key + 1)"
  244. contents = contents + "\n----------\n"
  245. contents = contents + str
  246. self.OCRResultString = contents
  247. if isCreatPDF {
  248. if index >= (photoArray?.count ?? 0) - 1 {
  249. var savePath = self.fileSavePath.stringByAppendingPathComponent("Untitled OCR").stringByAppendingPathExtension("pdf")
  250. savePath = self.getUniqueFilePath(savePath)
  251. if self.isSaveAsText {
  252. var savetextPath = self.fileSavePath.stringByAppendingPathComponent("Untitled OCR").stringByAppendingPathExtension("txt")
  253. savetextPath = self.getUniqueFilePath(savetextPath)
  254. try? self.OCRResultString.write(to: URL(fileURLWithPath: savetextPath), atomically: true, encoding: .utf8)
  255. NSWorkspace.shared.selectFile(savetextPath, inFileViewerRootedAtPath: "")
  256. }
  257. KMGOCRManager.default().createPDFFile(savePath, imagePaths: self.photoArray, results: (self.results as! [Any]), scale: 1.0)
  258. DispatchQueue.main.async {
  259. self.completeBlock?(savePath, self.errorArray as! Array<Any>, self.errorOCRArray as! Array<Any>)
  260. }
  261. } else {
  262. let pre = Float(index + 1) / (Float(photoArray?.count ?? 0) * 1.0)
  263. DispatchQueue.main.async {
  264. self.imageTopdfDelegate?.imageToPDFMethod(self, progress: pre)
  265. }
  266. }
  267. } else {
  268. if index >= (photoArray?.count ?? 0) - 1 {
  269. var savePath = kImageToPDFFolderPath?.stringByAppendingPathComponent("Untitled OCR").stringByAppendingPathExtension("pdf")
  270. KMGOCRManager.default().createPDFFile(savePath, imagePaths: self.photoArray, results: (self.results as! [Any]), scale: 1.0)
  271. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 3){
  272. if FileManager.default.fileExists(atPath: savePath ?? "") {
  273. let appPDF = self.appendPDF
  274. let newPdf = CPDFDocument.init(url: URL(fileURLWithPath: savePath ?? ""))
  275. for i in 0 ..< (newPdf?.pageCount ?? 0) {
  276. let page = newPdf?.page(at: i)
  277. appPDF?.insertPageObject(page, at: appPDF?.pageCount ?? 0)
  278. }
  279. var isSuccessfully = false
  280. let attributes = NSMutableDictionary(dictionary: appPDF!.documentAttributes()!, copyItems: true)
  281. if ((appPDF?.isEncrypted) != nil) {
  282. attributes.setValue(self.password, forKey: (kCGPDFContextUserPassword as NSString) as String)
  283. attributes.setValue(self.password, forKey: (kCGPDFContextOwnerPassword as NSString) as String)
  284. isSuccessfully = appPDF?.write(toFile: self.fileSavePath, withOptions: (attributes as? [CPDFDocumentWriteOption : Any])) ?? false
  285. } else {
  286. isSuccessfully = appPDF?.write(toFile: self.fileSavePath) ?? false
  287. }
  288. if self.isSaveAsText {
  289. var savetextPath = kImageToPDFFolderPath?.stringByAppendingPathComponent("Untitled OCR").stringByAppendingPathExtension("txt")
  290. if self.saveAsTestPath.isEmpty == false {
  291. savetextPath = self.saveAsTestPath.stringByAppendingPathComponent("Untitled OCR").stringByAppendingPathExtension("txt")
  292. }
  293. savetextPath = self.getUniqueFilePath(savetextPath ?? "")
  294. try? self.OCRResultString.write(to: URL(fileURLWithPath: savetextPath ?? ""), atomically: true, encoding: .utf8)
  295. NSWorkspace.shared.selectFile(savetextPath, inFileViewerRootedAtPath: "")
  296. }
  297. try? FileManager.default.removeItem(atPath: savePath ?? "")
  298. DispatchQueue.main.async {
  299. self.completeBlock?(self.fileSavePath, self.errorArray as! Array<Any>, self.errorOCRArray as! Array<Any>)
  300. }
  301. }
  302. }
  303. }else{
  304. let pre = Float(index + 1) / (Float(photoArray?.count ?? 0) * 1.0)
  305. DispatchQueue.main.async {
  306. self.imageTopdfDelegate?.imageToPDFMethod(self, progress: pre)
  307. }
  308. }
  309. }
  310. } else {
  311. let filePath: String = photoArray?[index] as! String
  312. let model = KMImageModel(filepath: filePath)
  313. let tString = model.photoName.deletingPathExtension.lastPathComponent
  314. var savePath = fileSavePath.stringByAppendingPathComponent(tString).stringByAppendingPathExtension("pdf")
  315. savePath = getUniqueFilePath(savePath)
  316. KMGOCRManager.default().createPDFFile(savePath, imagePaths: [filePath], results: [results as Any], scale: 1.0)
  317. var tFileName = fileSavePath.stringByAppendingPathComponent(tString).stringByAppendingPathExtension("txt")
  318. tFileName = getUniqueFilePath(tFileName)
  319. if isSaveAsText {
  320. var string: String = ""
  321. if results!.count > 0 {
  322. guard let firstResult: KMGOCRResult = results?.first else {
  323. return
  324. }
  325. string = firstResult.text
  326. try? string.write(toFile: tFileName, atomically: true, encoding: .utf8)
  327. }
  328. }
  329. if index < (photoArray?.count ?? 0) - 1 {
  330. let pre = Float(index + 1) / Float(photoArray?.count ?? 1)
  331. DispatchQueue.main.async {
  332. self.imageTopdfDelegate?.imageToPDFMethod(self, progress: pre)
  333. }
  334. } else {
  335. DispatchQueue.main.async {
  336. self.completeBlock?(savePath, self.errorArray as! Array<Any>, self.errorOCRArray as! Array<Any>)
  337. }
  338. }
  339. }
  340. }
  341. }
  342. static func supportedImageTypes() -> [String] {
  343. return ["jpg", "cur", "bmp", "jpeg", "gif", "png", "tiff", "tif", "ico", "icns", "tga", "psd", "eps", "hdr", "jp2", "jpc", "pict", "sgi"]
  344. }
  345. }