KMBatchConvertOperation.swift 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  1. //
  2. // KMBatchConvertOperation.swift
  3. // PDF Reader Pro
  4. //
  5. // Created by liujiajie on 2023/11/28.
  6. //
  7. import Foundation
  8. @objc enum KMConvertWay: Int {
  9. case KM = 0
  10. case FP
  11. }
  12. class KMBatchConvertOperation: KMBatchOperation, CPDFConverterDelegate, CPDFConverterFPDelegate{
  13. lazy var convertWay: KMConvertWay = {
  14. let way: KMConvertWay?
  15. if self.operateFile?.convertType == .WordStandard {
  16. way = .KM
  17. } else {
  18. way = .FP
  19. }
  20. return way!
  21. }()
  22. var fpPDFConverter: CPDFConverterFP?
  23. var converter: CPDFConverter?
  24. var pdfDocument: CPDFDocument?
  25. var isAllInOneSheet: Bool = false
  26. // 是否使用OCR
  27. var isAllowOCR = false
  28. var ocrLanguage: COCRLanguage?
  29. deinit {
  30. }
  31. init(file: KMBatchOperateFile, convertType: KMConvertWithPDFType) {
  32. super.init(file: file)
  33. self.operateFile?.convertType = convertType
  34. self.hasExcuting = false
  35. self.hasFinished = false
  36. // self.pdfDocument = CPDFDocument(url: URL(fileURLWithPath: file.filePath))
  37. // if ((self.pdfDocument?.isLocked) != nil) {
  38. // self.pdfDocument?.unlock(withPassword: file.password)
  39. // }
  40. }
  41. override func start() {
  42. if !self.isCancelled {
  43. self.pdfDocument = CPDFDocument(url: URL(fileURLWithPath: self.operateFile?.filePath ?? ""))
  44. if let data = self.pdfDocument?.isLocked, data {
  45. self.pdfDocument?.unlock(withPassword: self.operateFile?.password)
  46. }
  47. willChangeValue(forKey: "isExecuting")
  48. self.hasExcuting = true
  49. didChangeValue(forKey: "isExecuting")
  50. if !FileManager.default.fileExists(atPath: self.operateFile?.filePath ?? "") {
  51. self.delegate?.fileOperateFailed?(self.operateFile!, error: self.errorWithMsg(KMLocalizedString("File Not Exist", nil)), info: self.operateFile!.removePasswordInfo)
  52. self.willChangeValue(forKey: "isFinished")
  53. self.hasFinished = true
  54. self.didChangeValue(forKey: "isFinished")
  55. return
  56. }
  57. if self.pdfDocument == nil {
  58. self.delegate?.fileOperateFailed?(self.operateFile!, error: self.errorWithMsg(KMLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", nil)), info: self.operateFile!.removeWatermarkInfo)
  59. self.willChangeValue(forKey: "isFinished")
  60. self.hasFinished = true
  61. self.didChangeValue(forKey: "isFinished")
  62. return
  63. }
  64. if !self.pdfDocument!.allowsPrinting || !self.pdfDocument!.allowsCopying {
  65. self.delegate?.fileOperateFailed?(self.operateFile!, error: self.errorWithMsg(KMLocalizedString("This is a secured document. Editing is not permitted.", nil)), info: self.operateFile!.removeWatermarkInfo)
  66. self.willChangeValue(forKey: "isFinished")
  67. self.hasFinished = true
  68. self.didChangeValue(forKey: "isFinished")
  69. return
  70. }
  71. self.operateFile?.outputFilePath = (self.operateFile?.currentConvertParameter?.fetchDestinationFilepath()) ?? ""
  72. if self.operateFile?.currentConvertParameter?.pagesArray?.count ?? 0 < 1 {
  73. let error = NSError(domain: "LocalError", code: 0, userInfo: [NSLocalizedDescriptionKey: KMLocalizedString("Invalid page range or the page number is out of range. Please try again.", nil)])
  74. self.delegate?.fileOperateFailed?(self.operateFile!, error: error, info: self.operateFile!.currentConvertParameter!)
  75. self.willChangeValue(forKey: "isFinished")
  76. self.hasFinished = true
  77. self.didChangeValue(forKey: "isFinished")
  78. return
  79. }
  80. if self.operateFile?.convertType == .WordAdvance || self.operateFile?.convertType == .WordStandard {
  81. self.converter = CPDFConverterWord.init(url: URL(fileURLWithPath: operateFile?.filePath ?? ""), password: operateFile?.password)
  82. self.converter!.delegate = self
  83. let options = CPDFConvertWordOptions()
  84. options.layoutOptions = self.operateFile?.advanceWordParameter.isRetainLayout ?? false ? .retainPageLayout : .retainFlowingText
  85. options.isContainAnnotations = true
  86. options.isContainImages = true
  87. options.isAllowOCR = self.isAllowOCR
  88. if (self.isAllowOCR) {
  89. options.isContainOCRBgImage = true
  90. options.isAILayoutAnalysis = true
  91. if let language = self.ocrLanguage {
  92. options.language = language
  93. } else {
  94. options.language = .english
  95. }
  96. } else {
  97. options.isContainOCRBgImage = false
  98. options.isAILayoutAnalysis = false
  99. }
  100. self.converter!.convert(toFilePath: operateFile!.outputFilePath, pageIndexs: operateFile?.currentConvertParameter?.pagesArray, options: options)
  101. return
  102. }
  103. if self.operateFile?.convertType == .Excel {
  104. self.converter = CPDFConverterExcel.init(url: URL(fileURLWithPath: operateFile?.filePath ?? ""), password: operateFile?.password)
  105. self.converter!.delegate = self
  106. let options = CPDFConvertExcelOptions()
  107. options.isContainAnnotations = true
  108. options.isContainImages = true
  109. // options.isContainOCRBgImage = false
  110. options.isAllowOCR = self.isAllowOCR
  111. if (self.isAllowOCR) {
  112. options.isAILayoutAnalysis = true
  113. if let language = self.ocrLanguage {
  114. options.language = language
  115. } else {
  116. options.language = .english
  117. }
  118. } else {
  119. options.isAILayoutAnalysis = false
  120. }
  121. options.contentOptions = operateFile?.excelParameter.excelContentOption ?? .allContent
  122. options.worksheetOptions = operateFile?.excelParameter.excelWorksheetOption ?? .forEachPage
  123. self.converter!.convert(toFilePath: operateFile?.outputFilePath, pageIndexs: operateFile?.currentConvertParameter?.pagesArray, options: options)
  124. return
  125. }
  126. if self.operateFile?.convertType == .PowerPoint {
  127. self.converter = CPDFConverterPPT.init(url: URL(fileURLWithPath: operateFile?.filePath ?? ""), password: operateFile?.password)
  128. self.converter!.delegate = self
  129. let options = CPDFConvertPPTOptions()
  130. options.isContainAnnotations = true
  131. options.isContainImages = true
  132. options.isAllowOCR = self.isAllowOCR
  133. if (self.isAllowOCR) {
  134. options.isContainOCRBgImage = true
  135. options.isAILayoutAnalysis = true
  136. if let language = self.ocrLanguage {
  137. options.language = language
  138. } else {
  139. options.language = .english
  140. }
  141. } else {
  142. options.isContainOCRBgImage = false
  143. options.isAILayoutAnalysis = false
  144. }
  145. self.converter!.convert(toFilePath: operateFile?.outputFilePath, pageIndexs: operateFile?.currentConvertParameter?.pagesArray, options: options)
  146. return
  147. }
  148. if self.operateFile?.convertType == .CSV && self.operateFile?.CSVParameter.isExtreactTabel ?? false {
  149. self.converter = CPDFConverterCsv.init(url: URL(fileURLWithPath: operateFile?.filePath ?? ""), password: operateFile?.password)
  150. self.converter!.delegate = self
  151. let options = CPDFConvertCsvOptions()
  152. self.converter!.convert(toFilePath: operateFile?.outputFilePath, pageIndexs: operateFile?.currentConvertParameter?.pagesArray, options: options)
  153. return
  154. }
  155. if self.operateFile?.convertType == .RTF {
  156. self.converter = CPDFConverterRtf.init(url: URL(fileURLWithPath: operateFile?.filePath ?? ""), password: operateFile?.password)
  157. self.converter!.delegate = self
  158. let options = CPDFConvertRtfOptions()
  159. options.isContainAnnotations = true
  160. // options.isAllowOCR = true
  161. options.isContainImages = true
  162. options.isAllowOCR = self.isAllowOCR
  163. if (self.isAllowOCR) {
  164. options.isContainOCRBgImage = true
  165. if let language = self.ocrLanguage {
  166. options.language = language
  167. } else {
  168. options.language = .english
  169. }
  170. } else {
  171. options.isContainOCRBgImage = false
  172. }
  173. self.converter!.convert(toFilePath: operateFile?.outputFilePath, pageIndexs: operateFile?.currentConvertParameter?.pagesArray, options: options)
  174. return
  175. }
  176. if self.operateFile?.convertType == .HTML {
  177. self.converter = CPDFConverterHtml.init(url: URL(fileURLWithPath: operateFile?.filePath ?? ""), password: operateFile?.password)
  178. self.converter!.delegate = self
  179. let options = CPDFConvertHtmlOptions()
  180. options.isContainAnnotations = true
  181. options.isContainImages = true
  182. options.isAllowOCR = self.isAllowOCR
  183. if (self.isAllowOCR) {
  184. options.isContainOCRBgImage = true
  185. if let language = self.ocrLanguage {
  186. options.language = language
  187. } else {
  188. options.language = .english
  189. }
  190. } else {
  191. options.isContainOCRBgImage = false
  192. }
  193. self.converter!.convert(toFilePath: operateFile?.outputFilePath, pageIndexs: operateFile?.currentConvertParameter?.pagesArray, options: options)
  194. return
  195. }
  196. if self.operateFile?.convertType == .Text {
  197. self.converter = CPDFConverterTxt.init(url: URL(fileURLWithPath: operateFile?.filePath ?? ""), password: operateFile?.password)
  198. self.converter!.delegate = self
  199. let options = CPDFConvertTxtOptions()
  200. options.isAllowOCR = self.isAllowOCR
  201. if (self.isAllowOCR) {
  202. if let language = self.ocrLanguage {
  203. options.language = language
  204. } else {
  205. options.language = .english
  206. }
  207. }
  208. self.converter!.convert(toFilePath: operateFile?.outputFilePath, pageIndexs: operateFile?.currentConvertParameter?.pagesArray, options: options)
  209. return
  210. }
  211. if self.operateFile?.convertType == .Json {
  212. if let data = self.operateFile?.JSONParameter.isExtreactTabel, data {
  213. self.converter = CPDFConverterJsonTable(url: URL(fileURLWithPath: operateFile?.filePath ?? ""), password: self.operateFile?.password)
  214. } else {
  215. self.converter = CPDFConverterJson(url: URL(fileURLWithPath: operateFile?.filePath ?? ""), password: self.operateFile?.password)
  216. }
  217. self.converter?.delegate = self
  218. let options = CPDFConvertJsonOptions()
  219. options.isAllowOCR = self.isAllowOCR
  220. if (self.isAllowOCR) {
  221. if let language = self.ocrLanguage {
  222. options.language = language
  223. } else {
  224. options.language = .english
  225. }
  226. } else {
  227. }
  228. self.converter!.convert(toFilePath: operateFile?.outputFilePath, pageIndexs: operateFile?.currentConvertParameter?.pagesArray, options: options)
  229. return
  230. }
  231. let op: [String:Any] = [CPDFConvertOptionsKey.imageDPI.rawValue:operateFile?.dpi as Any,CPDFConvertOptionsKey.allInOneSheet.rawValue:(operateFile?.currentConvertParameter?.allInOneSheet ?? false)]
  232. self.fpPDFConverter = CPDFConverterFP()
  233. self.fpPDFConverter!.setDelegate(self)
  234. self.fpPDFConverter?.convertPDF(atPath: operateFile?.filePath, pdfPassword: operateFile?.password, pdfPageIndexs: operateFile?.currentConvertParameter?.pagesArray, destDocType: operateFile?.currentConvertParameter?.extensionString(), destDocPath: operateFile?.outputFilePath, moreOptions:op)
  235. }else {
  236. willChangeValue(forKey: "isFinished")
  237. willChangeValue(forKey: "isExecuting")
  238. hasExcuting = false
  239. hasFinished = true
  240. didChangeValue(forKey: "isExecuting")
  241. didChangeValue(forKey: "isFinished")
  242. }
  243. }
  244. override func cancel() {
  245. // super.cancel()
  246. if isExecuting {
  247. self.fpPDFConverter?.stopConvertsionIfNeed()
  248. self.operateFile?.currentConvertParameter?.status = .Waiting
  249. if FileManager.default.fileExists(atPath: (operateFile?.currentConvertParameter?.outPutPath)!) { try? FileManager.default.removeItem(atPath: (operateFile!.currentConvertParameter?.outPutPath)!)
  250. }
  251. self.delegate?.fileOperateCanceled?(self.operateFile!, info: self.operateFile!.currentConvertParameter!)
  252. willChangeValue(forKey: "isFinished")
  253. hasFinished = true
  254. didChangeValue(forKey: "isFinished")
  255. } else {
  256. willChangeValue(forKey: "isCancelled")
  257. hasCanceled = true
  258. didChangeValue(forKey: "isCancelled")
  259. }
  260. }
  261. //MARK: FPPDFConverterDelegate
  262. func fppdfConverter(_ converter: Any!, didStartConversion error: Error!) {
  263. DispatchQueue.main.async {
  264. if (error != nil){
  265. self.delegate?.fileOperateFailed?(self.operateFile!, error: error! as NSError, info: (self.operateFile?.currentConvertParameter!)!)
  266. }else {
  267. self.delegate?.fileBeginOperate?(self.operateFile!, info: (self.operateFile?.currentConvertParameter!)!)
  268. }
  269. }
  270. }
  271. func fppdfConverter(_ converter: Any!, didEndConversion error: Error!) {
  272. // DispatchQueue.main.async {
  273. if (error != nil){
  274. self.delegate?.fileOperateFailed?(self.operateFile!, error: error! as NSError, info: (self.operateFile?.currentConvertParameter!)!)
  275. }else {
  276. self.delegate?.fileOperateSuccessed?(self.operateFile!, info: (self.operateFile?.currentConvertParameter!)!)
  277. }
  278. self.fpPDFConverter?.setDelegate(nil)
  279. if self.viewController?.view.window?.isVisible == true {
  280. willChangeValue(forKey: "isFinished")
  281. hasFinished = true
  282. didChangeValue(forKey: "isFinished")
  283. }
  284. // }
  285. }
  286. func fppdfConverter(_ converter: Any!, pageIndex pageIndexA: UInt, progress: UInt) {
  287. }
  288. func fppdfConverter(_ converter: Any!, convertPDFPageIndex pdfPageIndexA: UInt, writeWordPageIndex wordPageIndexA: UInt, finshedWordPageCount wordPageCountA: UInt) {
  289. let totalPages: Int = self.operateFile?.convertInfo?.pagesArray?.count ?? 0
  290. self.delegate?.fileOperating?(self.operateFile!, progress: CGFloat(wordPageCountA)/CGFloat(totalPages), info: (self.operateFile?.currentConvertParameter!)!)
  291. }
  292. //MARK: CPDFConverterDelegate
  293. func converter(_ converter: CPDFConverter!, didStartConvert error: Error!) {
  294. DispatchQueue.main.async {
  295. if (error != nil){
  296. self.delegate?.fileOperateFailed?(self.operateFile!, error: error! as NSError, info: (self.operateFile?.currentConvertParameter!)!)
  297. }else {
  298. self.delegate?.fileBeginOperate?(self.operateFile!, info: (self.operateFile?.currentConvertParameter!)!)
  299. }
  300. }
  301. }
  302. func converter(_ converter: CPDFConverter!, pageIndex index: UInt, pageCount count: UInt) {
  303. let totalPages: Int = self.operateFile?.convertInfo?.pagesArray?.count ?? 0
  304. self.delegate?.fileOperating?(self.operateFile!, progress: CGFloat(index)/CGFloat(totalPages), info: (self.operateFile?.currentConvertParameter!)!)
  305. }
  306. func converter(_ converter: CPDFConverter!, didEndConvert error: Error!) {
  307. if (error != nil){
  308. var erroeString = ""
  309. let err: NSError = error! as NSError
  310. switch err.code {
  311. case CPDFConverterEncryptError:
  312. erroeString = KMLocalizedString("Password required or incorrect password. Please re-enter your password and try again",nil)
  313. case CPDFConverterPermissionError:
  314. erroeString = KMLocalizedString("The license doesn't allow the permission",nil);
  315. case CPDFConverterMallocError:
  316. erroeString = KMLocalizedString("Malloc failure",nil);
  317. case CPDFConverterUnknownError:
  318. erroeString = KMLocalizedString("Unknown error in processing conversion. Please try again later",nil);
  319. case CPDFConverterPDFUnknownError:
  320. erroeString = KMLocalizedString("Unknown error in processing PDF. Please try again later",nil);
  321. case CPDFConverterPDFFileError:
  322. erroeString = KMLocalizedString("File not found or could not be opened. Check if your file exists or choose another file to convert",nil);
  323. case CPDFConverterPDFFormatError:
  324. erroeString = KMLocalizedString("File not in PDF format or corruptead. Change a PDF file and try again",nil);
  325. case CPDFConverterPDFSecurityError:
  326. erroeString = KMLocalizedString("Unsupported security scheme",nil);
  327. break;
  328. case CPDFConverterPDFPageError:
  329. erroeString = KMLocalizedString("Page not found or content error",nil);
  330. break;
  331. default:
  332. erroeString = KMLocalizedString("Table not found",nil);
  333. }
  334. let newError = NSError(domain: "", code: err.code, userInfo: [NSLocalizedFailureReasonErrorKey: erroeString])
  335. self.delegate?.fileOperateFailed?(self.operateFile!, error: newError, info: (self.operateFile?.currentConvertParameter!)!)
  336. }else {
  337. self.delegate?.fileOperateSuccessed?(self.operateFile!, info: (self.operateFile?.currentConvertParameter!)!)
  338. }
  339. if self.converter != nil && self.converter?.delegate != nil {
  340. self.converter?.delegate = nil
  341. }
  342. if self.viewController?.view.window?.isVisible == true {
  343. willChangeValue(forKey: "isFinished")
  344. hasFinished = true
  345. didChangeValue(forKey: "isFinished")
  346. }
  347. }
  348. }