KMImageToPDFMethod.swift 17 KB

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