KMImageToPDFMethod.swift 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  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(_ results: [KMGOCRResult]?, OCRImageAtIndex index: Int) {
  223. if isOCR {
  224. if isMerge {
  225. self.results.add(results 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. var str: String = ""
  235. if results!.count > 0 {
  236. guard let firstResult: KMGOCRResult = results?.first else {
  237. return
  238. }
  239. str = firstResult.text
  240. }
  241. contents = contents + "\n"
  242. contents = contents + "Page" + "\(key + 1)"
  243. contents = contents + "\n----------\n"
  244. contents = contents + str
  245. self.OCRResultString = contents
  246. if isCreatPDF {
  247. if index >= (photoArray?.count ?? 0) - 1 {
  248. var savePath = self.fileSavePath.stringByAppendingPathComponent("Untitled OCR").stringByAppendingPathExtension("pdf")
  249. savePath = self.getUniqueFilePath(savePath)
  250. if self.isSaveAsText {
  251. var savetextPath = self.fileSavePath.stringByAppendingPathComponent("Untitled OCR").stringByAppendingPathExtension("txt")
  252. savetextPath = self.getUniqueFilePath(savetextPath)
  253. try? self.OCRResultString.write(to: URL(fileURLWithPath: savetextPath), atomically: true, encoding: .utf8)
  254. NSWorkspace.shared.selectFile(savetextPath, inFileViewerRootedAtPath: "")
  255. }
  256. KMGOCRManager.default().createPDFFile(savePath, imagePaths: self.photoArray, results: (self.results as! [Any]), scale: 1.0)
  257. DispatchQueue.main.async {
  258. self.completeBlock?(savePath, self.errorArray as! Array<Any>, self.errorOCRArray as! Array<Any>)
  259. }
  260. } else {
  261. let pre = Float(index + 1) / (Float(photoArray?.count ?? 0) * 1.0)
  262. DispatchQueue.main.async {
  263. self.imageTopdfDelegate?.imageToPDFMethod(self, progress: pre)
  264. }
  265. }
  266. } else {
  267. if index >= (photoArray?.count ?? 0) - 1 {
  268. var savePath = kImageToPDFFolderPath?.stringByAppendingPathComponent("Untitled OCR").stringByAppendingPathExtension("pdf")
  269. KMGOCRManager.default().createPDFFile(savePath, imagePaths: self.photoArray, results: (self.results as! [Any]), scale: 1.0)
  270. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 3){
  271. if FileManager.default.fileExists(atPath: savePath ?? "") {
  272. let appPDF = self.appendPDF
  273. let newPdf = CPDFDocument.init(url: URL(fileURLWithPath: savePath ?? ""))
  274. for i in 0 ..< (newPdf?.pageCount ?? 0) {
  275. let page = newPdf?.page(at: i)
  276. appPDF?.insertPageObject(page, at: appPDF?.pageCount ?? 0)
  277. }
  278. var isSuccessfully = false
  279. let attributes = NSMutableDictionary(dictionary: appPDF!.documentAttributes()!, copyItems: true)
  280. if ((appPDF?.isEncrypted) != nil) {
  281. attributes.setValue(self.password, forKey: (kCGPDFContextUserPassword as NSString) as String)
  282. attributes.setValue(self.password, forKey: (kCGPDFContextOwnerPassword as NSString) as String)
  283. isSuccessfully = appPDF?.write(toFile: self.fileSavePath, withOptions: (attributes as? [CPDFDocumentWriteOption : Any])) ?? false
  284. } else {
  285. isSuccessfully = appPDF?.write(toFile: self.fileSavePath) ?? false
  286. }
  287. if self.isSaveAsText {
  288. var savetextPath = kImageToPDFFolderPath?.stringByAppendingPathComponent("Untitled OCR").stringByAppendingPathExtension("txt")
  289. savetextPath = self.getUniqueFilePath(savetextPath ?? "")
  290. try? self.OCRResultString.write(to: URL(fileURLWithPath: savetextPath ?? ""), atomically: true, encoding: .utf8)
  291. NSWorkspace.shared.selectFile(savetextPath, inFileViewerRootedAtPath: "")
  292. }
  293. try? FileManager.default.removeItem(atPath: savePath ?? "")
  294. DispatchQueue.main.async {
  295. self.completeBlock?(self.fileSavePath, self.errorArray as! Array<Any>, self.errorOCRArray as! Array<Any>)
  296. }
  297. }
  298. }
  299. }else{
  300. let pre = Float(index + 1) / (Float(photoArray?.count ?? 0) * 1.0)
  301. DispatchQueue.main.async {
  302. self.imageTopdfDelegate?.imageToPDFMethod(self, progress: pre)
  303. }
  304. }
  305. }
  306. } else {
  307. let filePath: String = photoArray?[index] as! String
  308. let model = KMImageModel(filepath: filePath)
  309. let tString = model.photoName.deletingPathExtension.lastPathComponent
  310. var savePath = fileSavePath.stringByAppendingPathComponent(tString).stringByAppendingPathExtension("pdf")
  311. savePath = getUniqueFilePath(savePath)
  312. KMGOCRManager.default().createPDFFile(savePath, imagePaths: [filePath], results: [results as Any], scale: 1.0)
  313. var tFileName = fileSavePath.stringByAppendingPathComponent(tString).stringByAppendingPathExtension("txt")
  314. tFileName = getUniqueFilePath(tFileName)
  315. if isSaveAsText {
  316. var string: String = ""
  317. if results!.count > 0 {
  318. guard let firstResult: KMGOCRResult = results?.first else {
  319. return
  320. }
  321. string = firstResult.text
  322. try? string.write(toFile: tFileName, atomically: true, encoding: .utf8)
  323. }
  324. }
  325. if index < (photoArray?.count ?? 0) - 1 {
  326. let pre = Float(index + 1) / Float(photoArray?.count ?? 1)
  327. DispatchQueue.main.async {
  328. self.imageTopdfDelegate?.imageToPDFMethod(self, progress: pre)
  329. }
  330. } else {
  331. DispatchQueue.main.async {
  332. self.completeBlock?(savePath, self.errorArray as! Array<Any>, self.errorOCRArray as! Array<Any>)
  333. }
  334. }
  335. }
  336. }
  337. }
  338. static func supportedImageTypes() -> [String] {
  339. return ["jpg", "cur", "bmp", "jpeg", "gif", "png", "tiff", "tif", "ico", "icns", "tga", "psd", "eps", "hdr", "jp2", "jpc", "pict", "sgi"]
  340. }
  341. }