KMBatchConvertOperation.swift 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  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. deinit {
  27. }
  28. init(file: KMBatchOperateFile, convertType: KMConvertWithPDFType) {
  29. super.init(file: file)
  30. self.operateFile?.convertType = convertType
  31. self.hasExcuting = false
  32. self.hasFinished = false
  33. // self.pdfDocument = CPDFDocument(url: URL(fileURLWithPath: file.filePath))
  34. // if ((self.pdfDocument?.isLocked) != nil) {
  35. // self.pdfDocument?.unlock(withPassword: file.password)
  36. // }
  37. }
  38. override func start() {
  39. if !self.isCancelled {
  40. self.pdfDocument = CPDFDocument(url: URL(fileURLWithPath: self.operateFile?.filePath ?? ""))
  41. if let data = self.pdfDocument?.isLocked, data {
  42. self.pdfDocument?.unlock(withPassword: self.operateFile?.password)
  43. }
  44. willChangeValue(forKey: "isExecuting")
  45. self.hasExcuting = true
  46. didChangeValue(forKey: "isExecuting")
  47. if !FileManager.default.fileExists(atPath: self.operateFile?.filePath ?? "") {
  48. self.delegate?.fileOperateFailed?(self.operateFile!, error: self.errorWithMsg(KMLocalizedString("File Not Exist", nil)), info: self.operateFile!.removePasswordInfo)
  49. self.willChangeValue(forKey: "isFinished")
  50. self.hasFinished = true
  51. self.didChangeValue(forKey: "isFinished")
  52. return
  53. }
  54. if self.pdfDocument == nil {
  55. 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)
  56. self.willChangeValue(forKey: "isFinished")
  57. self.hasFinished = true
  58. self.didChangeValue(forKey: "isFinished")
  59. return
  60. }
  61. if !self.pdfDocument!.allowsPrinting || !self.pdfDocument!.allowsCopying {
  62. self.delegate?.fileOperateFailed?(self.operateFile!, error: self.errorWithMsg(KMLocalizedString("This is a secured document. Editing is not permitted.", nil)), info: self.operateFile!.removeWatermarkInfo)
  63. self.willChangeValue(forKey: "isFinished")
  64. self.hasFinished = true
  65. self.didChangeValue(forKey: "isFinished")
  66. return
  67. }
  68. self.operateFile?.outputFilePath = (self.operateFile?.currentConvertParameter?.fetchDestinationFilepath()) ?? ""
  69. if self.operateFile?.currentConvertParameter?.pagesArray?.count ?? 0 < 1 {
  70. 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)])
  71. self.delegate?.fileOperateFailed?(self.operateFile!, error: error, info: self.operateFile!.currentConvertParameter!)
  72. self.willChangeValue(forKey: "isFinished")
  73. self.hasFinished = true
  74. self.didChangeValue(forKey: "isFinished")
  75. return
  76. }
  77. if self.operateFile?.convertType == .WordAdvance || self.operateFile?.convertType == .WordStandard {
  78. self.converter = CPDFConverterWord.init(url: URL(fileURLWithPath: operateFile?.filePath ?? ""), password: operateFile?.password)
  79. self.converter!.delegate = self
  80. let options = CPDFConvertWordOptions()
  81. options.layoutOptions = self.operateFile?.advanceWordParameter.isRetainLayout ?? false ? .retainPageLayout : .retainFlowingText
  82. options.isContainAnnotations = true
  83. options.isContainImages = true
  84. self.converter!.convert(toFilePath: operateFile!.outputFilePath, pageIndexs: operateFile?.currentConvertParameter?.pagesArray, options: options)
  85. return
  86. }
  87. if self.operateFile?.convertType == .Excel {
  88. self.converter = CPDFConverterExcel.init(url: URL(fileURLWithPath: operateFile?.filePath ?? ""), password: operateFile?.password)
  89. self.converter!.delegate = self
  90. let options = CPDFConvertExcelOptions()
  91. options.isContainAnnotations = true
  92. options.isContainImages = true
  93. // options.isContainOCRBgImage = false
  94. options.contentOptions = operateFile?.excelParameter.excelContentOption ?? .allContent
  95. options.worksheetOptions = operateFile?.excelParameter.excelWorksheetOption ?? .forEachPage
  96. self.converter!.convert(toFilePath: operateFile?.outputFilePath, pageIndexs: operateFile?.currentConvertParameter?.pagesArray, options: options)
  97. return
  98. }
  99. if self.operateFile?.convertType == .PowerPoint {
  100. self.converter = CPDFConverterPPT.init(url: URL(fileURLWithPath: operateFile?.filePath ?? ""), password: operateFile?.password)
  101. self.converter!.delegate = self
  102. let options = CPDFConvertPPTOptions()
  103. options.isContainAnnotations = true
  104. options.isContainImages = true
  105. self.converter!.convert(toFilePath: operateFile?.outputFilePath, pageIndexs: operateFile?.currentConvertParameter?.pagesArray, options: options)
  106. return
  107. }
  108. if self.operateFile?.convertType == .CSV && self.operateFile?.CSVParameter.isExtreactTabel ?? false {
  109. self.converter = CPDFConverterCsv.init(url: URL(fileURLWithPath: operateFile?.filePath ?? ""), password: operateFile?.password)
  110. self.converter!.delegate = self
  111. let options = CPDFConvertCsvOptions()
  112. self.converter!.convert(toFilePath: operateFile?.outputFilePath, pageIndexs: operateFile?.currentConvertParameter?.pagesArray, options: options)
  113. return
  114. }
  115. if self.operateFile?.convertType == .RTF {
  116. self.converter = CPDFConverterRtf.init(url: URL(fileURLWithPath: operateFile?.filePath ?? ""), password: operateFile?.password)
  117. self.converter!.delegate = self
  118. let options = CPDFConvertRtfOptions()
  119. options.isContainAnnotations = true
  120. // options.isAllowOCR = true
  121. options.isContainImages = true
  122. self.converter!.convert(toFilePath: operateFile?.outputFilePath, pageIndexs: operateFile?.currentConvertParameter?.pagesArray, options: options)
  123. return
  124. }
  125. if self.operateFile?.convertType == .HTML {
  126. self.converter = CPDFConverterHtml.init(url: URL(fileURLWithPath: operateFile?.filePath ?? ""), password: operateFile?.password)
  127. self.converter!.delegate = self
  128. let options = CPDFConvertHtmlOptions()
  129. options.isContainAnnotations = true
  130. // options.isAllowOCR = true
  131. options.isContainImages = true
  132. self.converter!.convert(toFilePath: operateFile?.outputFilePath, pageIndexs: operateFile?.currentConvertParameter?.pagesArray, options: options)
  133. return
  134. }
  135. if self.operateFile?.convertType == .Text {
  136. self.converter = CPDFConverterTxt.init(url: URL(fileURLWithPath: operateFile?.filePath ?? ""), password: operateFile?.password)
  137. self.converter!.delegate = self
  138. let options = CPDFConvertTxtOptions()
  139. // options.isAllowOCR = true
  140. self.converter!.convert(toFilePath: operateFile?.outputFilePath, pageIndexs: operateFile?.currentConvertParameter?.pagesArray, options: options)
  141. return
  142. }
  143. let op: [String:Any] = [CPDFConvertOptionsKey.imageDPI.rawValue:operateFile?.dpi as Any,CPDFConvertOptionsKey.allInOneSheet.rawValue:(operateFile?.currentConvertParameter?.allInOneSheet ?? false)]
  144. self.fpPDFConverter = CPDFConverterFP()
  145. self.fpPDFConverter!.setDelegate(self)
  146. self.fpPDFConverter?.convertPDF(atPath: operateFile?.filePath, pdfPassword: operateFile?.password, pdfPageIndexs: operateFile?.currentConvertParameter?.pagesArray, destDocType: operateFile?.currentConvertParameter?.extensionString(), destDocPath: operateFile?.outputFilePath, moreOptions:op)
  147. }else {
  148. willChangeValue(forKey: "isFinished")
  149. willChangeValue(forKey: "isExecuting")
  150. hasExcuting = false
  151. hasFinished = true
  152. didChangeValue(forKey: "isExecuting")
  153. didChangeValue(forKey: "isFinished")
  154. }
  155. }
  156. override func cancel() {
  157. // super.cancel()
  158. if isExecuting {
  159. self.fpPDFConverter?.stopConvertsionIfNeed()
  160. self.operateFile?.currentConvertParameter?.status = .Waiting
  161. if FileManager.default.fileExists(atPath: (operateFile?.currentConvertParameter?.outPutPath)!) { try? FileManager.default.removeItem(atPath: (operateFile!.currentConvertParameter?.outPutPath)!)
  162. }
  163. self.delegate?.fileOperateCanceled?(self.operateFile!, info: self.operateFile!.currentConvertParameter!)
  164. willChangeValue(forKey: "isFinished")
  165. hasFinished = true
  166. didChangeValue(forKey: "isFinished")
  167. } else {
  168. willChangeValue(forKey: "isCancelled")
  169. hasCanceled = true
  170. didChangeValue(forKey: "isCancelled")
  171. }
  172. }
  173. //MARK: FPPDFConverterDelegate
  174. func fppdfConverter(_ converter: Any!, didStartConversion error: Error!) {
  175. DispatchQueue.main.async {
  176. if (error != nil){
  177. self.delegate?.fileOperateFailed?(self.operateFile!, error: error! as NSError, info: (self.operateFile?.currentConvertParameter!)!)
  178. }else {
  179. self.delegate?.fileBeginOperate?(self.operateFile!, info: (self.operateFile?.currentConvertParameter!)!)
  180. }
  181. }
  182. }
  183. func fppdfConverter(_ converter: Any!, didEndConversion error: Error!) {
  184. // DispatchQueue.main.async {
  185. if (error != nil){
  186. self.delegate?.fileOperateFailed?(self.operateFile!, error: error! as NSError, info: (self.operateFile?.currentConvertParameter!)!)
  187. }else {
  188. self.delegate?.fileOperateSuccessed?(self.operateFile!, info: (self.operateFile?.currentConvertParameter!)!)
  189. }
  190. self.fpPDFConverter?.setDelegate(nil)
  191. willChangeValue(forKey: "isFinished")
  192. hasFinished = true
  193. didChangeValue(forKey: "isFinished")
  194. // }
  195. }
  196. func fppdfConverter(_ converter: Any!, pageIndex pageIndexA: UInt, progress: UInt) {
  197. }
  198. func fppdfConverter(_ converter: Any!, convertPDFPageIndex pdfPageIndexA: UInt, writeWordPageIndex wordPageIndexA: UInt, finshedWordPageCount wordPageCountA: UInt) {
  199. let totalPages: Int = self.operateFile?.convertInfo?.pagesArray?.count ?? 0
  200. self.delegate?.fileOperating?(self.operateFile!, progress: CGFloat(wordPageCountA)/CGFloat(totalPages), info: (self.operateFile?.currentConvertParameter!)!)
  201. }
  202. //MARK: CPDFConverterDelegate
  203. func converter(_ converter: CPDFConverter!, didStartConvert error: Error!) {
  204. DispatchQueue.main.async {
  205. if (error != nil){
  206. self.delegate?.fileOperateFailed?(self.operateFile!, error: error! as NSError, info: (self.operateFile?.currentConvertParameter!)!)
  207. }else {
  208. self.delegate?.fileBeginOperate?(self.operateFile!, info: (self.operateFile?.currentConvertParameter!)!)
  209. }
  210. }
  211. }
  212. func converter(_ converter: CPDFConverter!, pageIndex index: UInt, pageCount count: UInt) {
  213. let totalPages: Int = self.operateFile?.convertInfo?.pagesArray?.count ?? 0
  214. self.delegate?.fileOperating?(self.operateFile!, progress: CGFloat(index)/CGFloat(totalPages), info: (self.operateFile?.currentConvertParameter!)!)
  215. }
  216. func converter(_ converter: CPDFConverter!, didEndConvert error: Error!) {
  217. if (error != nil){
  218. var erroeString = ""
  219. let err: NSError = error! as NSError
  220. switch err.code {
  221. case CPDFConverterEncryptError:
  222. erroeString = KMLocalizedString("Password required or incorrect password. Please re-enter your password and try again",nil)
  223. case CPDFConverterPermissionError:
  224. erroeString = KMLocalizedString("The license doesn't allow the permission",nil);
  225. case CPDFConverterMallocError:
  226. erroeString = KMLocalizedString("Malloc failure",nil);
  227. case CPDFConverterUnknownError:
  228. erroeString = KMLocalizedString("Unknown error in processing conversion. Please try again later",nil);
  229. case CPDFConverterPDFUnknownError:
  230. erroeString = KMLocalizedString("Unknown error in processing PDF. Please try again later",nil);
  231. case CPDFConverterPDFFileError:
  232. erroeString = KMLocalizedString("File not found or could not be opened. Check if your file exists or choose another file to convert",nil);
  233. case CPDFConverterPDFFormatError:
  234. erroeString = KMLocalizedString("File not in PDF format or corruptead. Change a PDF file and try again",nil);
  235. case CPDFConverterPDFSecurityError:
  236. erroeString = KMLocalizedString("Unsupported security scheme",nil);
  237. break;
  238. case CPDFConverterPDFPageError:
  239. erroeString = KMLocalizedString("Page not found or content error",nil);
  240. break;
  241. default:
  242. erroeString = KMLocalizedString("Table not found",nil);
  243. }
  244. let newError = NSError(domain: "", code: err.code, userInfo: [NSLocalizedFailureReasonErrorKey: erroeString])
  245. self.delegate?.fileOperateFailed?(self.operateFile!, error: newError, info: (self.operateFile?.currentConvertParameter!)!)
  246. }else {
  247. self.delegate?.fileOperateSuccessed?(self.operateFile!, info: (self.operateFile?.currentConvertParameter!)!)
  248. }
  249. if self.converter != nil && self.converter?.delegate != nil {
  250. self.converter?.delegate = nil
  251. }
  252. willChangeValue(forKey: "isFinished")
  253. hasFinished = true
  254. didChangeValue(forKey: "isFinished")
  255. }
  256. }