KMImageToPDFMethod.swift 17 KB

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