KMBatchManager.swift 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831
  1. //
  2. // KMBatchManager.swift
  3. // PDF Master
  4. //
  5. // Created by lizhe on 2023/2/17.
  6. //
  7. import Cocoa
  8. enum KMBatchManagerSate: Int, CaseIterable {
  9. case unknow = 0
  10. case processing
  11. case complete
  12. case error
  13. }
  14. let kBacthFilesProcessNotification = "kBacthFilesProcessNotification"
  15. let kBacthProcessNotification = "kBacthProcessNotification"
  16. class KMBatchManager: NSObject {
  17. public static let manager = KMBatchManager()
  18. fileprivate(set) var state: KMBatchManagerSate = .unknow
  19. var filesData: [KMBatchProcessingTableViewModel] = []
  20. var batchFilesData: [KMBatchProcessingTableViewModel] {
  21. get {
  22. var resultArray:[KMBatchProcessingTableViewModel] = []
  23. for item in filesData {
  24. if !item.isLock {
  25. resultArray.append(item)
  26. }
  27. }
  28. return resultArray
  29. }
  30. }
  31. func batch(type: KMBatchCollectionViewType, data: KMBatchSettingItemViewModel) {
  32. let panel = NSOpenPanel()
  33. panel.canChooseFiles = false
  34. panel.canChooseDirectories = true
  35. panel.canCreateDirectories = true
  36. panel.beginSheetModal(for: NSWindow.currentWindow()) { response in
  37. if response == .cancel {
  38. return
  39. }
  40. let outputFolderPath = (panel.url?.path)!
  41. //
  42. self.batchUnkown()
  43. switch type {
  44. case .convertPDF:
  45. self.convertPDFExport(data: data, outputFolderPath: outputFolderPath)
  46. break
  47. case .OCR:
  48. self.convertOCRExport(data: data, outputFolderPath: outputFolderPath)
  49. break
  50. case .compress:
  51. self.compressExport(data: data, outputFolderPath: outputFolderPath)
  52. break
  53. case .security:
  54. self.securityExport(data: data, outputFolderPath: outputFolderPath)
  55. break
  56. case .watermark:
  57. break
  58. case .background:
  59. self.backgroundApplay(data: data, outputFolderPath: outputFolderPath)
  60. break
  61. case .headerAndFooter:
  62. break
  63. case .batesNumber:
  64. break
  65. case .batchRemove:
  66. self.removeApplay(data: data, outputFolderPath: outputFolderPath)
  67. break
  68. case .imageToPDF:
  69. self.imageToPDFExport(data: data, outputFolderPath: outputFolderPath)
  70. break
  71. default:
  72. KMPrint("找不到")
  73. break
  74. }
  75. //
  76. self.batchProgress()
  77. }
  78. }
  79. }
  80. //MARK: 批量
  81. extension KMBatchManager {
  82. //MARK: 转档
  83. func convertPDFExport(data: KMBatchSettingItemViewModel, outputFolderPath: String) {
  84. self.convertFile(outputFolderPath: outputFolderPath, data: data, filesData: self.batchFilesData)
  85. }
  86. func convertFile(outputFolderPath: String, data: KMBatchSettingItemViewModel, filesData: [KMBatchProcessingTableViewModel]) {
  87. if filesData.count != 0 {
  88. DispatchQueue.global().async {
  89. for i in 0..<filesData.count {
  90. let item = filesData[i]
  91. //创建Document
  92. let filePath = item.filePath
  93. let document = self.fetchDocument(filePath: filePath, model: item)
  94. let settingData = data as? KMBatchConvertPDFViewModel ?? KMBatchConvertPDFViewModel()
  95. var fileName = filePath.deletingPathExtension.lastPathComponent
  96. if ((fileName.isEmpty)) {
  97. fileName = NSLocalizedString("Untitled", comment: "")
  98. }
  99. let convert = self.addConvertParameter(settingData)
  100. let pageCount = document.pageCount
  101. //获取page
  102. var pages:[Int] = []
  103. for i in 0..<pageCount {
  104. pages.append(Int(i)+1)
  105. }
  106. convert.outputFolderPath = outputFolderPath
  107. convert.filePath = filePath
  108. convert.outputFileName = fileName
  109. convert.pages = pages
  110. convert.isAllowOCR = settingData.needRecognizeText
  111. convert.ocrLanguage = settingData.languageType
  112. item.state = .clock
  113. KMPDFConvertManager.defaultManager.convert(convert: convert, progress: { [unowned self] progressValue in
  114. print("转档进度 - \(progressValue)")
  115. let progress = Float(progressValue) / Float(pageCount)
  116. self.itemProgress(item: item, processValue: progress)
  117. }, completion: { [unowned self] finished, error in
  118. if finished {
  119. if FileManager.default.fileExists(atPath: outputFolderPath) {
  120. NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: outputFolderPath)])
  121. }
  122. self.itemSuccess(item: item)
  123. } else {
  124. self.itemFailure(item: item, error: error! as NSError)
  125. }
  126. if i == filesData.count - 1 {
  127. self.batchSuccess()
  128. }
  129. })
  130. }
  131. }
  132. }
  133. }
  134. func addConvertParameter(_ data: KMBatchConvertPDFViewModel) -> KMPDFConvert {
  135. let settingData = data
  136. var convert = KMPDFConvert()
  137. switch settingData.convertPDFType {
  138. case .word:
  139. convert = KMPDFConvertWord()
  140. if settingData.layoutSettingType == .flowingText {
  141. convert.isAllInOneSheet = false
  142. } else {
  143. convert.isAllInOneSheet = true
  144. }
  145. case .excel:
  146. convert = KMPDFConvertExcel()
  147. if settingData.excelSetting == .separate {
  148. convert.isAllInOneSheet = false
  149. convert.isExtractTable = false
  150. } else if settingData.excelSetting == .format {
  151. convert.isAllInOneSheet = true
  152. convert.isExtractTable = false
  153. } else if settingData.excelSetting == .tables {
  154. convert.isAllInOneSheet = false
  155. convert.isExtractTable = true
  156. switch settingData.excelTablesType {
  157. case .oneTable:
  158. convert.extractTableIndex = 0
  159. case .pageTable:
  160. convert.extractTableIndex = 1
  161. case .allTable:
  162. convert.extractTableIndex = 2
  163. default:
  164. KMPrint("未找到")
  165. }
  166. }
  167. case .ppt:
  168. convert = KMPDFConvertPPT()
  169. case .csv:
  170. convert = KMPDFConvertCSV()
  171. if settingData.csvOnlyTables {
  172. convert.isExtractTable = true
  173. switch settingData.excelTablesType {
  174. case .oneTable:
  175. convert.extractTableIndex = 0
  176. case .pageTable:
  177. convert.extractTableIndex = 1
  178. case .allTable:
  179. convert.extractTableIndex = 2
  180. default:
  181. KMPrint("未找到")
  182. }
  183. } else {
  184. convert.isExtractTable = false
  185. }
  186. case .image:
  187. convert = KMPDFConvertImage()
  188. convert.convertType = data.imageType
  189. var dpi: Int = 150
  190. if data.imageDpiIndex == 0 {
  191. dpi = 50
  192. } else if data.imageDpiIndex == 1 {
  193. dpi = 72
  194. } else if data.imageDpiIndex == 2 {
  195. dpi = 96
  196. } else if data.imageDpiIndex == 3 {
  197. dpi = 150
  198. } else if data.imageDpiIndex == 4 {
  199. dpi = 300
  200. } else if data.imageDpiIndex == 5 {
  201. dpi = 600
  202. } else {
  203. dpi = 150
  204. }
  205. if (convert.convertType == .jpeg) {
  206. (convert as! KMPDFConvertImage).imageType = .JPEG
  207. (convert as! KMPDFConvertImage).imageDpi = dpi
  208. } else if (convert.convertType == .png) {
  209. (convert as! KMPDFConvertImage).imageType = .PNG
  210. (convert as! KMPDFConvertImage).imageDpi = dpi
  211. } else {
  212. (convert as! KMPDFConvertImage).imageDpi = 150
  213. }
  214. case .html:
  215. convert = KMPDFConvertHTML()
  216. case .rtf:
  217. convert = KMPDFConvertRTF()
  218. case .json:
  219. convert = KMPDFConvertJson()
  220. if settingData.jsonType == .extractText {
  221. convert.isAllInOneSheet = false
  222. } else {
  223. convert.isAllInOneSheet = true
  224. }
  225. case .text:
  226. convert = KMPDFConvertText()
  227. default:
  228. KMPrint("不清楚")
  229. }
  230. return convert
  231. }
  232. //MARK: OCR
  233. func convertOCRExport(data: KMBatchSettingItemViewModel, outputFolderPath: String) {
  234. self.convertOCR(outputFolderPath: outputFolderPath, data: data as! KMOCRModel, filesData: self.batchFilesData)
  235. }
  236. func convertOCR(outputFolderPath: String, data: KMOCRModel, filesData: [KMBatchProcessingTableViewModel]?) {
  237. guard let filesData = filesData else { return }
  238. for i in 0..<filesData.count {
  239. let item = (filesData[i])
  240. let document = CPDFDocument.init(url: URL(fileURLWithPath: item.filePath))
  241. if document != nil {
  242. //计算需要处理的页面
  243. var fileName = item.filePath.deletingPathExtension.lastPathComponent
  244. if ((fileName.isEmpty)) {
  245. fileName = NSLocalizedString("Untitled", comment: "")
  246. }
  247. let path = outputFolderPath + "/" + fileName + ".pdf"
  248. self.convertOCR(outputFolderPath: outputFolderPath, document: document!, fileName: fileName, data: data) { [unowned self] progress in
  249. self.itemProgress(item: item, processValue: progress)
  250. } complete: { [unowned self] document, text, error in
  251. if error == nil {
  252. self.itemSuccess(item: item)
  253. } else {
  254. self.itemFailure(item: item, error: error! as NSError)
  255. }
  256. if i == filesData.count - 1 {
  257. self.batchSuccess()
  258. }
  259. }
  260. }
  261. }
  262. }
  263. func convertOCR(outputFolderPath: String,
  264. document: CPDFDocument,
  265. fileName: String,
  266. data: KMOCRModel,
  267. progress: @escaping KMOCRManagerOCRProgress,
  268. complete: @escaping KMOCRManagerOCRComplete) {
  269. //计算需要处理的页面
  270. let path = outputFolderPath + "/" + fileName + ".pdf"
  271. KMOCRManager.manager.convertBatchOCR(document: document, saveFilePath: path, model: data, progress: { [unowned self] progressValue in
  272. progress(progressValue)
  273. }) { [unowned self] document, text, error in
  274. complete(document, text, error)
  275. }
  276. }
  277. //MARK: 压缩
  278. func compressExport(data: KMBatchSettingItemViewModel, outputFolderPath: String) {
  279. self.compressFile(outputFolderPath: outputFolderPath, data: (data as? KMCompressSettingModel)!, filesData: self.batchFilesData)
  280. }
  281. func compressFile(outputFolderPath: String, data: KMCompressSettingModel, filesData: [KMBatchProcessingTableViewModel]) {
  282. if filesData.count != 0 {
  283. for i in 0..<filesData.count {
  284. let item = filesData[i]
  285. let document = CPDFDocument.init(url: URL(fileURLWithPath: item.filePath))
  286. if document != nil {
  287. var fileName = item.filePath.deletingPathExtension.lastPathComponent
  288. if ((fileName.isEmpty)) {
  289. fileName = NSLocalizedString("Untitled", comment: "")
  290. }
  291. let path = outputFolderPath + "/" + fileName + ".pdf"
  292. KMCompressManager.shared.compress(documentURL: URL(fileURLWithPath: item.filePath), fileURL: URL(fileURLWithPath: path), limit: false, model: data) { currentPage, totalPages in
  293. let progress = Float(currentPage) / Float(totalPages)
  294. self.itemProgress(item: item, processValue: progress)
  295. } cancelHandler: {
  296. return false
  297. } completionHandler: { [unowned self] isFinish in
  298. if isFinish {
  299. self.itemSuccess(item: item)
  300. } else {
  301. self.itemFailure(item: item, error: nil)
  302. }
  303. if i == filesData.count - 1 {
  304. self.batchSuccess()
  305. }
  306. }
  307. }
  308. }
  309. }
  310. }
  311. //MARK: 安全
  312. func securityExport(data: KMBatchSettingItemViewModel, outputFolderPath: String) {
  313. self.securityFile(outputFolderPath: outputFolderPath, data: data as! KMBatchSecurityViewModel, filesData: self.batchFilesData)
  314. }
  315. func securityFile(outputFolderPath: String, data: KMBatchSecurityViewModel, filesData: [KMBatchProcessingTableViewModel]) {
  316. if filesData.count != 0 {
  317. for i in 0..<filesData.count {
  318. let item = filesData[i]
  319. let docuemt = CPDFDocument.init(url: URL(fileURLWithPath: item.filePath))
  320. if (docuemt != nil) {
  321. var fileName = item.filePath.deletingPathExtension.lastPathComponent
  322. if ((fileName.isEmpty)) {
  323. fileName = NSLocalizedString("Untitled", comment: "")
  324. }
  325. let path = outputFolderPath + "/" + fileName + ".pdf"
  326. var options: [CPDFDocumentWriteOption : Any] = [:]
  327. //开启密码
  328. if data.isOpenPassword &&
  329. !data.openPasswordString.isEmpty {
  330. options.updateValue(data.openPasswordString, forKey: .userPasswordOption)
  331. }
  332. //
  333. //权限密码
  334. if data.isPermission &&
  335. !data.permissionString.isEmpty {
  336. options.updateValue(data.permissionString, forKey: .ownerPasswordOption)
  337. }
  338. // 限制打印
  339. if data.restrictOptions.contains(.print) {
  340. options.updateValue(false, forKey: .allowsPrintingOption)
  341. } else {
  342. options.updateValue(true, forKey: .allowsPrintingOption)
  343. }
  344. //限制复制
  345. if data.restrictOptions.contains(.copy) {
  346. options.updateValue(false, forKey: .allowsCopyingOption)
  347. } else {
  348. options.updateValue(true, forKey: .allowsCopyingOption)
  349. }
  350. let result = docuemt!.write(toFile: path, withOptions: options)
  351. // let result = docuemt!.write(to: URL(fileURLWithPath: path), withOptions: options)
  352. if result {
  353. KMPrint("成功")
  354. self.itemSuccess(item: item)
  355. } else {
  356. KMPrint("失败")
  357. self.itemFailure(item: item, error: nil)
  358. }
  359. if i == filesData.count - 1 {
  360. self.batchSuccess()
  361. NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: outputFolderPath)])
  362. }
  363. }
  364. }
  365. }
  366. }
  367. //MARK: 水印
  368. func waterMarkApplay(data: KMBatchSettingItemViewModel, outputFolderPath: String) {
  369. }
  370. func waterMarkFile(outputFolderPath: String, data: KMBatchSettingItemViewModel, filesData: [KMBatchProcessingTableViewModel]?) {
  371. }
  372. //MARK: 背景
  373. func backgroundApplay(data: KMBatchSettingItemViewModel, outputFolderPath: String) {
  374. if let data = data as? KMBatchBackgroundModel {
  375. self.backgroundFile(outputFolderPath: outputFolderPath, data: data, filesData: self.batchFilesData)
  376. }
  377. }
  378. func backgroundFile(outputFolderPath: String, data: KMBatchBackgroundModel, filesData: [KMBatchProcessingTableViewModel]) {
  379. if filesData.count != 0 {
  380. for i in 0..<filesData.count {
  381. let item = filesData[i]
  382. var fileName = item.filePath.deletingPathExtension.lastPathComponent
  383. if ((fileName.isEmpty)) {
  384. fileName = NSLocalizedString("Untitled", comment: "")
  385. }
  386. let path = outputFolderPath + "/" + fileName + ".pdf"
  387. let document = CPDFDocument.init(url: URL(fileURLWithPath: item.filePath))
  388. if (document?.allowsPrinting == false || document?.allowsCopying == false) {
  389. let alert = NSAlert()
  390. alert.alertStyle = .critical
  391. alert.messageText = "此文档不允许修改"
  392. alert.runModal()
  393. return
  394. }
  395. if let background = document?.background(), let model = data.backgroundModel {
  396. KMBackgroundManager.defaultManager.updateBackground(background, withModel: model)
  397. var pages = Array(0..<Int(document!.pageCount))
  398. let pageIndexString = pages.isEmpty ? "" : pages.map { "\($0)" }.joined(separator: ",")
  399. background.pageString = pageIndexString
  400. background.update()
  401. }
  402. if (FileManager.default.fileExists(atPath: path)) {
  403. try?FileManager.default.removeItem(atPath: path)
  404. }
  405. let result = document?.write(to: URL(fileURLWithPath: path)) ?? false
  406. if (result) {
  407. KMPrint("removeFile成功")
  408. self.itemSuccess(item: item)
  409. } else {
  410. KMPrint("removeFile失败")
  411. self.itemFailure(item: item, error: nil)
  412. }
  413. if i == filesData.count - 1 {
  414. self.batchSuccess()
  415. }
  416. NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: path)])
  417. }
  418. }
  419. }
  420. //MARK: 页眉页脚
  421. func headAndFooterApplay(data: KMBatchSettingItemViewModel, outputFolderPath: String) {
  422. }
  423. func headAndFooterFile(outputFolderPath: String, data: KMBatchSettingItemViewModel, filesData: [KMBatchProcessingTableViewModel]?) {
  424. }
  425. //MARK: 贝茨码
  426. func batesApplay(data: KMBatchSettingItemViewModel, outputFolderPath: String) {
  427. }
  428. func batesFile(outputFolderPath: String, data: KMBatchSettingItemViewModel, filesData: [KMBatchProcessingTableViewModel]?) {
  429. }
  430. //MARK: 移除
  431. func removeApplay(data: KMBatchSettingItemViewModel, outputFolderPath: String) {
  432. self.removeFile(outputFolderPath: outputFolderPath, data: data as! KMBatchRemoveViewModel, filesData: self.batchFilesData)
  433. }
  434. func removeFile(outputFolderPath: String, data: KMBatchRemoveViewModel, filesData: [KMBatchProcessingTableViewModel]) {
  435. if filesData.count != 0 {
  436. for i in 0..<filesData.count {
  437. let item = filesData[i]
  438. // DispatchQueue.global().async {
  439. var fileName = item.filePath.deletingPathExtension.lastPathComponent
  440. if ((fileName.isEmpty)) {
  441. fileName = NSLocalizedString("Untitled", comment: "")
  442. }
  443. let path = outputFolderPath + "/" + fileName + ".pdf"
  444. let document = CPDFDocument.init(url: URL(fileURLWithPath: item.filePath))
  445. if document != nil {
  446. if (document!.allowsPrinting == false || document!.allowsCopying == false) {
  447. let alert = NSAlert()
  448. alert.alertStyle = .critical
  449. alert.messageText = "此文档不允许修改"
  450. alert.runModal()
  451. return
  452. }
  453. if (data.options.contains(.security)) {
  454. }
  455. if (data.options.contains(.batesNumber)) {
  456. let property = document!.bates()
  457. property?.clear()
  458. }
  459. if (data.options.contains(.headerAndFooter)) {
  460. let property = document!.headerFooter()
  461. property?.clear()
  462. }
  463. if (data.options.contains(.background)) {
  464. let property = document!.background()
  465. property?.clear()
  466. }
  467. if (data.options.contains(.watermark)) {
  468. let array: Array<CPDFWatermark> = document!.watermarks() ?? []
  469. for model in array {
  470. document!.removeWatermark(model)
  471. }
  472. }
  473. if (FileManager.default.fileExists(atPath: path)) {
  474. try?FileManager.default.removeItem(atPath: path)
  475. }
  476. let result = document!.write(to: URL(fileURLWithPath: path))
  477. if (result) {
  478. KMPrint("removeFile成功")
  479. self.itemSuccess(item: item)
  480. } else {
  481. KMPrint("removeFile失败")
  482. self.itemFailure(item: item, error: nil)
  483. }
  484. if i == filesData.count - 1 {
  485. self.batchSuccess()
  486. }
  487. NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: outputFolderPath)])
  488. }
  489. // }
  490. }
  491. }
  492. }
  493. //MARK: 图片转PDF
  494. func imageToPDFExport(data: KMBatchSettingItemViewModel, outputFolderPath: String) {
  495. self.imageToPDFFile(outputFolderPath: outputFolderPath, data: data as! KMBatchImageToPDFModel, filesData: self.batchFilesData)
  496. }
  497. func imageToPDFFile(outputFolderPath: String, data: KMBatchImageToPDFModel, filesData: [KMBatchProcessingTableViewModel]) {
  498. if filesData.count != 0 {
  499. self.batchProgress()
  500. if data.isNewPDF {
  501. if data.isMergeAll {
  502. let item = filesData[0]
  503. var fileName = item.filePath.deletingPathExtension.lastPathComponent
  504. let path = outputFolderPath + "/" + fileName + ".pdf"
  505. var pdfDocument = CPDFDocument()
  506. for item in filesData {
  507. pdfDocument?.km_insert(image: item.image, at: pdfDocument?.pageCount ?? 0)
  508. }
  509. if data.isOCR {
  510. let model = KMOCRModel()
  511. model.showType = .page
  512. model.saveAsPDF = true
  513. model.ocrType = data.ocrType
  514. model.languageType = data.languageType
  515. model.needTxT = data.isExtractText
  516. model.pageRangeType = .all
  517. //计算需要处理的页面
  518. let pages:[Int] = KMOCRManager.fetchPageIndex(document: pdfDocument!, model: model)
  519. model.pageRange = pages
  520. self.batchProgress()
  521. self.convertOCR(outputFolderPath: outputFolderPath, document: pdfDocument!, fileName: fileName, data: model) { progress in
  522. self.batchProgress()
  523. } complete: { document, text, error in
  524. self.batchSuccess()
  525. }
  526. } else {
  527. pdfDocument?.write(toFile: path)
  528. }
  529. self.batchSuccess()
  530. } else {
  531. for i in 0..<filesData.count {
  532. let item = filesData[i]
  533. if data.isOCR {
  534. var fileName = item.filePath.deletingPathExtension.lastPathComponent
  535. let path = outputFolderPath + "/" + fileName + ".pdf"
  536. var pdfDocument = CPDFDocument()
  537. for item in filesData {
  538. pdfDocument?.km_insert(image: item.image, at: pdfDocument?.pageCount ?? 0)
  539. }
  540. let model = KMOCRModel()
  541. model.showType = .page
  542. model.saveAsPDF = true
  543. model.ocrType = data.ocrType
  544. model.languageType = data.languageType
  545. model.needTxT = data.isExtractText
  546. model.pageRangeType = .all
  547. //计算需要处理的页面
  548. let pages:[Int] = KMOCRManager.fetchPageIndex(document: pdfDocument!, model: model)
  549. model.pageRange = pages
  550. self.itemProgress(item: item, processValue: 0)
  551. self.convertOCR(outputFolderPath: outputFolderPath, document: pdfDocument!, fileName: fileName, data: model) { [unowned self] progress in
  552. self.itemProgress(item: item, processValue: progress)
  553. } complete: { [unowned self] document, text, error in
  554. self.itemSuccess(item: item)
  555. if i == filesData.count - 1 {
  556. self.batchSuccess()
  557. }
  558. }
  559. } else {
  560. var fileName = item.filePath.deletingPathExtension.lastPathComponent
  561. let path = outputFolderPath + "/" + fileName + ".pdf"
  562. var pdfDocument = CPDFDocument()
  563. pdfDocument?.km_insert(image: item.image, at: pdfDocument?.pageCount ?? 0)
  564. let success = pdfDocument?.write(toFile: path)
  565. if success != nil {
  566. self.batchSuccess()
  567. } else {
  568. self.batchFailure()
  569. }
  570. }
  571. }
  572. }
  573. } else {
  574. var fileName = data.selectFilePath.deletingPathExtension.lastPathComponent
  575. let path = outputFolderPath + "/" + fileName + ".pdf"
  576. var pdfDocument = CPDFDocument(url: NSURL(fileURLWithPath: data.selectFilePath) as URL)
  577. let count: Int = Int(pdfDocument?.pageCount ?? 0)
  578. for item in filesData {
  579. pdfDocument?.km_insert(image: item.image, at: pdfDocument?.pageCount ?? 0)
  580. }
  581. if data.isOCR {
  582. let model = KMOCRModel()
  583. model.showType = .page
  584. model.saveAsPDF = true
  585. model.ocrType = data.ocrType
  586. model.languageType = data.languageType
  587. model.needTxT = data.isExtractText
  588. model.pageRangeType = .all
  589. //计算需要处理的页面
  590. let pages:[Int] = KMOCRManager.fetchPageIndex(document: pdfDocument!, model: model)
  591. model.pageRange = pages
  592. self.convertOCR(outputFolderPath: outputFolderPath, document: pdfDocument!, fileName: fileName, data: model) { progress in
  593. } complete: { document, text, error in
  594. if (error != nil) {
  595. self.batchFailure()
  596. } else {
  597. self.batchSuccess()
  598. }
  599. }
  600. } else {
  601. pdfDocument?.write(toFile: path)
  602. }
  603. self.batchSuccess()
  604. }
  605. }
  606. }
  607. }
  608. //MARK: private
  609. extension KMBatchManager {
  610. func fetchDocument(filePath: String, model: KMBatchProcessingTableViewModel) -> CPDFDocument {
  611. var document = CPDFDocument(url: URL(fileURLWithPath: filePath))
  612. if model.pageRange == .all {
  613. } else {
  614. let data = KMOCRModel()
  615. data.pageRangeType = model.pageRange
  616. data.pageRangeString = model.pageRangeString
  617. let pages:[Int] = KMOCRManager.fetchPageIndex(document: document!, model: data)
  618. var tempDocument = CPDFDocument()
  619. for i in 0..<pages.count {
  620. let page = document?.page(at: UInt(i))
  621. tempDocument?.insertPageObject(page, at: tempDocument?.pageCount ?? 0)
  622. }
  623. let fileName = filePath.deletingPathExtension.lastPathComponent
  624. let isSuccess = tempDocument?.write(toFile: self.fetchTempFilePath(fileName: fileName))
  625. if isSuccess != nil {
  626. document = tempDocument
  627. }
  628. }
  629. return document ?? CPDFDocument()
  630. }
  631. func fetchTempFilePath(fileName: String) -> String {
  632. let floderPath = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.applicationSupportDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).last?.stringByAppendingPathComponent(Bundle.main.bundleIdentifier!).stringByAppendingPathComponent("BatchTemp")
  633. let filePath = floderPath?.stringByAppendingPathComponent("\(fileName).pdf")
  634. if let data = floderPath, !FileManager.default.fileExists(atPath: data) {
  635. try?FileManager.default.createDirectory(atPath: data, withIntermediateDirectories: false)
  636. }
  637. if let data = filePath, !FileManager.default.fileExists(atPath: data) {
  638. FileManager.default.createFile(atPath: data, contents: nil)
  639. }
  640. return filePath ?? ""
  641. }
  642. func removeTempFilePath(filePath: String) {
  643. let fileName = filePath.deletingPathExtension.lastPathComponent
  644. let path = self.fetchTempFilePath(fileName: fileName)
  645. if (FileManager.default.fileExists(atPath: path)) {
  646. try?FileManager.default.removeItem(atPath: path)
  647. }
  648. }
  649. }
  650. //MARK: Alert
  651. extension KMBatchManager {
  652. func batchUnkown() {
  653. self.state = .unknow
  654. NotificationCenter.default.post(name: NSNotification.Name(kBacthProcessNotification), object: nil)
  655. }
  656. func batchProgress() {
  657. self.state = .processing
  658. NotificationCenter.default.post(name: NSNotification.Name(kBacthProcessNotification), object: nil)
  659. }
  660. func batchSuccess() {
  661. self.state = .complete
  662. NotificationCenter.default.post(name: NSNotification.Name(kBacthProcessNotification), object: nil)
  663. }
  664. func batchFailure() {
  665. self.state = .error
  666. NotificationCenter.default.post(name: NSNotification.Name(kBacthProcessNotification), object: nil)
  667. }
  668. func itemProgress(item: KMBatchProcessingTableViewModel, processValue: Float) {
  669. if processValue > 0.7 {
  670. item.state = .loading70
  671. } else {
  672. item.state = .loading
  673. }
  674. NotificationCenter.default.post(name: NSNotification.Name(kBacthFilesProcessNotification), object: item)
  675. }
  676. func itemSuccess(item: KMBatchProcessingTableViewModel) {
  677. self.removeTempFilePath(filePath: item.filePath)
  678. item.state = .success
  679. NotificationCenter.default.post(name: NSNotification.Name(kBacthFilesProcessNotification), object: item)
  680. }
  681. func itemFailure(item: KMBatchProcessingTableViewModel, error: NSError?) {
  682. self.removeTempFilePath(filePath: item.filePath)
  683. item.state = .error
  684. NotificationCenter.default.post(name: NSNotification.Name(kBacthFilesProcessNotification), object: item)
  685. guard let error = error else { return }
  686. var errorString = ""
  687. let myError: NSError = error as NSError
  688. if myError.code == 1 {
  689. errorString = NSLocalizedString("Password required or incorrect password. Please re-enter your password and try again", comment: "")
  690. } else if myError.code == 2 {
  691. errorString = NSLocalizedString("The license doesn't allow the permission", comment: "")
  692. } else if myError.code == 3 {
  693. errorString = NSLocalizedString("Malloc failure", comment: "")
  694. } else if myError.code == 4 {
  695. errorString = NSLocalizedString("Unknown error in processing conversion. Please try again later", comment: "")
  696. } else if myError.code == 5 {
  697. errorString = NSLocalizedString("Unknown error in processing PDF. Please try again later", comment: "")
  698. } else if myError.code == 6 {
  699. errorString = NSLocalizedString("File not found or could not be opened. Check if your file exists or choose another file to convert", comment: "")
  700. } else if myError.code == 7 {
  701. errorString = NSLocalizedString("File not in PDF format or corruptead. Change a PDF file and try again", comment: "")
  702. } else if myError.code == 8 {
  703. errorString = NSLocalizedString("Unsupported security scheme", comment: "")
  704. } else if myError.code == 9 {
  705. errorString = NSLocalizedString("Page not found or content error", comment: "")
  706. } else {
  707. errorString = NSLocalizedString("Table not found", comment: "")
  708. }
  709. let alert = NSAlert()
  710. alert.alertStyle = .critical
  711. alert.messageText = NSLocalizedString("Conversion Failed", comment: "")
  712. alert.informativeText = errorString
  713. alert.addButton(withTitle: NSLocalizedString("OK", comment: ""))
  714. alert.runModal()
  715. }
  716. }