KMBatchManager.swift 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991
  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. self.waterMarkApplay(data: data, outputFolderPath: outputFolderPath)
  58. break
  59. case .background:
  60. self.backgroundApplay(data: data, outputFolderPath: outputFolderPath)
  61. break
  62. case .headerAndFooter:
  63. self.headAndFooterApplay(data: data, outputFolderPath: outputFolderPath)
  64. break
  65. case .batesNumber:
  66. self.batesApplay(data: data, outputFolderPath: outputFolderPath)
  67. break
  68. case .batchRemove:
  69. self.removeApplay(data: data, outputFolderPath: outputFolderPath)
  70. break
  71. case .imageToPDF:
  72. self.imageToPDFExport(data: data, outputFolderPath: outputFolderPath)
  73. break
  74. default:
  75. KMPrint("找不到")
  76. break
  77. }
  78. //
  79. self.batchProgress()
  80. }
  81. }
  82. }
  83. //MARK: 批量
  84. extension KMBatchManager {
  85. //MARK: 转档
  86. func convertPDFExport(data: KMBatchSettingItemViewModel, outputFolderPath: String) {
  87. self.convertFile(outputFolderPath: outputFolderPath, data: data, filesData: self.batchFilesData)
  88. }
  89. func convertFile(outputFolderPath: String, data: KMBatchSettingItemViewModel, filesData: [KMBatchProcessingTableViewModel]) {
  90. guard !filesData.isEmpty else { return }
  91. func processFile(at index: Int) {
  92. guard index < filesData.count else {
  93. self.batchSuccess()
  94. return
  95. }
  96. let item = filesData[index]
  97. let filePath = item.filePath
  98. let document = self.fetchDocument(filePath: filePath, model: item)
  99. let settingData = data as? KMBatchConvertPDFViewModel ?? KMBatchConvertPDFViewModel()
  100. var path = self.fetchFilePath(type: .convertPDF, filePath: filePath, outputFolderPath: outputFolderPath)
  101. let convert = self.addConvertParameter(settingData)
  102. let pageCount = document.pageCount
  103. // 获取页面
  104. let pages: [Int] = Array(1...Int(pageCount))
  105. convert.outputFolderPath = outputFolderPath
  106. convert.filePath = filePath
  107. convert.outputFileName = path.deletingPathExtension.lastPathComponent
  108. convert.pages = pages
  109. convert.isAllowOCR = settingData.needRecognizeText
  110. convert.ocrLanguage = settingData.languageType
  111. item.state = .clock
  112. KMPDFConvertManager.defaultManager.convert(convert: convert, progress: { [unowned self] progressValue in
  113. print("转档进度 - \(progressValue)")
  114. let progress = Float(progressValue) / Float(pageCount)
  115. self.itemProgress(item: item, processValue: progress)
  116. }, completion: { [unowned self] finished, error in
  117. if finished {
  118. if FileManager.default.fileExists(atPath: outputFolderPath) {
  119. NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: outputFolderPath)])
  120. }
  121. self.itemSuccess(item: item)
  122. } else {
  123. self.itemFailure(item: item, error: error! as NSError)
  124. }
  125. processFile(at: index + 1)
  126. })
  127. }
  128. // 开始处理第一个文件
  129. processFile(at: 0)
  130. }
  131. func addConvertParameter(_ data: KMBatchConvertPDFViewModel) -> KMPDFConvert {
  132. let settingData = data
  133. var convert = KMPDFConvert()
  134. switch settingData.convertPDFType {
  135. case .word:
  136. convert = KMPDFConvertWord()
  137. if settingData.layoutSettingType == .flowingText {
  138. convert.isAllInOneSheet = false
  139. } else {
  140. convert.isAllInOneSheet = true
  141. }
  142. case .excel:
  143. convert = KMPDFConvertExcel()
  144. if settingData.excelSetting == .separate {
  145. convert.isAllInOneSheet = false
  146. convert.isExtractTable = false
  147. } else if settingData.excelSetting == .format {
  148. convert.isAllInOneSheet = true
  149. convert.isExtractTable = false
  150. } else if settingData.excelSetting == .tables {
  151. convert.isAllInOneSheet = false
  152. convert.isExtractTable = true
  153. switch settingData.excelTablesType {
  154. case .oneTable:
  155. convert.extractTableIndex = 0
  156. case .pageTable:
  157. convert.extractTableIndex = 1
  158. case .allTable:
  159. convert.extractTableIndex = 2
  160. default:
  161. KMPrint("未找到")
  162. }
  163. }
  164. case .ppt:
  165. convert = KMPDFConvertPPT()
  166. case .csv:
  167. convert = KMPDFConvertCSV()
  168. if settingData.csvOnlyTables {
  169. convert.isExtractTable = true
  170. switch settingData.excelTablesType {
  171. case .oneTable:
  172. convert.extractTableIndex = 0
  173. case .pageTable:
  174. convert.extractTableIndex = 1
  175. case .allTable:
  176. convert.extractTableIndex = 2
  177. default:
  178. KMPrint("未找到")
  179. }
  180. } else {
  181. convert.isExtractTable = false
  182. }
  183. case .image:
  184. convert = KMPDFConvertImage()
  185. convert.convertType = data.imageType
  186. var dpi: Int = 150
  187. if data.imageDpiIndex == 0 {
  188. dpi = 50
  189. } else if data.imageDpiIndex == 1 {
  190. dpi = 72
  191. } else if data.imageDpiIndex == 2 {
  192. dpi = 96
  193. } else if data.imageDpiIndex == 3 {
  194. dpi = 150
  195. } else if data.imageDpiIndex == 4 {
  196. dpi = 300
  197. } else if data.imageDpiIndex == 5 {
  198. dpi = 600
  199. } else {
  200. dpi = 150
  201. }
  202. if (convert.convertType == .jpeg) {
  203. (convert as! KMPDFConvertImage).imageType = .JPEG
  204. (convert as! KMPDFConvertImage).imageDpi = dpi
  205. } else if (convert.convertType == .png) {
  206. (convert as! KMPDFConvertImage).imageType = .PNG
  207. (convert as! KMPDFConvertImage).imageDpi = dpi
  208. } else {
  209. (convert as! KMPDFConvertImage).imageDpi = 150
  210. }
  211. case .html:
  212. convert = KMPDFConvertHTML()
  213. case .rtf:
  214. convert = KMPDFConvertRTF()
  215. case .json:
  216. convert = KMPDFConvertJson()
  217. if settingData.jsonType == .extractText {
  218. convert.isAllInOneSheet = false
  219. } else {
  220. convert.isAllInOneSheet = true
  221. }
  222. case .text:
  223. convert = KMPDFConvertText()
  224. default:
  225. KMPrint("不清楚")
  226. }
  227. return convert
  228. }
  229. //MARK: OCR
  230. func convertOCRExport(data: KMBatchSettingItemViewModel, outputFolderPath: String) {
  231. self.convertOCR(outputFolderPath: outputFolderPath, data: data as! KMOCRModel, filesData: self.batchFilesData)
  232. }
  233. func convertOCR(outputFolderPath: String, data: KMOCRModel, filesData: [KMBatchProcessingTableViewModel]?) {
  234. guard let filesData = filesData else { return }
  235. for i in 0..<filesData.count {
  236. let item = (filesData[i])
  237. let document = CPDFDocument.init(url: URL(fileURLWithPath: item.filePath))
  238. if document != nil {
  239. //计算需要处理的页面
  240. var path = self.fetchFilePath(type: .OCR, filePath: item.filePath, outputFolderPath: outputFolderPath)
  241. self.convertOCR(outputFolderPath: outputFolderPath, document: document!, fileName: path.deletingPathExtension.lastPathComponent, data: data) { [unowned self] progress in
  242. self.itemProgress(item: item, processValue: progress)
  243. } complete: { [unowned self] document, text, error in
  244. if error == nil {
  245. self.itemSuccess(item: item)
  246. } else {
  247. self.itemFailure(item: item, error: error! as NSError)
  248. }
  249. if i == filesData.count - 1 {
  250. self.batchSuccess()
  251. }
  252. }
  253. }
  254. }
  255. }
  256. func convertOCR(outputFolderPath: String,
  257. document: CPDFDocument,
  258. fileName: String,
  259. data: KMOCRModel,
  260. progress: @escaping KMOCRManagerOCRProgress,
  261. complete: @escaping KMOCRManagerOCRComplete) {
  262. //计算需要处理的页面
  263. let path = outputFolderPath + "/" + fileName + ".pdf"
  264. KMOCRManager.manager.convertBatchOCR(document: document, saveFilePath: path, model: data, progress: { [unowned self] progressValue in
  265. progress(progressValue)
  266. }) { [unowned self] document, text, error in
  267. complete(document, text, error)
  268. }
  269. }
  270. //MARK: 压缩
  271. func compressExport(data: KMBatchSettingItemViewModel, outputFolderPath: String) {
  272. self.compressFile(outputFolderPath: outputFolderPath, data: (data as? KMCompressSettingModel)!, filesData: self.batchFilesData)
  273. }
  274. func compressFile(outputFolderPath: String, data: KMCompressSettingModel, filesData: [KMBatchProcessingTableViewModel]) {
  275. if filesData.count != 0 {
  276. for i in 0..<filesData.count {
  277. let item = filesData[i]
  278. let document = CPDFDocument.init(url: URL(fileURLWithPath: item.filePath))
  279. if document != nil {
  280. var path = self.fetchFilePath(type: .compress, filePath: item.filePath, outputFolderPath: outputFolderPath)
  281. KMCompressManager.shared.compress(documentURL: URL(fileURLWithPath: item.filePath), fileURL: URL(fileURLWithPath: path), limit: false, model: data) { currentPage, totalPages in
  282. let progress = Float(currentPage) / Float(totalPages)
  283. self.itemProgress(item: item, processValue: progress)
  284. } cancelHandler: {
  285. return false
  286. } completionHandler: { [unowned self] isFinish in
  287. if isFinish {
  288. self.itemSuccess(item: item)
  289. } else {
  290. self.itemFailure(item: item, error: nil)
  291. }
  292. if i == filesData.count - 1 {
  293. self.batchSuccess()
  294. }
  295. }
  296. }
  297. }
  298. }
  299. }
  300. //MARK: 安全
  301. func securityExport(data: KMBatchSettingItemViewModel, outputFolderPath: String) {
  302. self.securityFile(outputFolderPath: outputFolderPath, data: data as! KMBatchSecurityViewModel, filesData: self.batchFilesData)
  303. }
  304. func securityFile(outputFolderPath: String, data: KMBatchSecurityViewModel, filesData: [KMBatchProcessingTableViewModel]) {
  305. if filesData.count != 0 {
  306. for i in 0..<filesData.count {
  307. let item = filesData[i]
  308. let docuemt = CPDFDocument.init(url: URL(fileURLWithPath: item.filePath))
  309. if (docuemt != nil) {
  310. var path = self.fetchFilePath(type: .security, filePath: item.filePath, outputFolderPath: outputFolderPath)
  311. var options: [CPDFDocumentWriteOption : Any] = [:]
  312. //开启密码
  313. if data.isOpenPassword &&
  314. !data.openPasswordString.isEmpty {
  315. options.updateValue(data.openPasswordString, forKey: .userPasswordOption)
  316. }
  317. //
  318. //权限密码
  319. if data.isPermission &&
  320. !data.permissionString.isEmpty {
  321. options.updateValue(data.permissionString, forKey: .ownerPasswordOption)
  322. }
  323. // 限制打印
  324. if data.restrictOptions.contains(.print) {
  325. options.updateValue(false, forKey: .allowsPrintingOption)
  326. } else {
  327. options.updateValue(true, forKey: .allowsPrintingOption)
  328. }
  329. //限制复制
  330. if data.restrictOptions.contains(.copy) {
  331. options.updateValue(false, forKey: .allowsCopyingOption)
  332. } else {
  333. options.updateValue(true, forKey: .allowsCopyingOption)
  334. }
  335. let result = docuemt!.write(toFile: path, withOptions: options)
  336. // let result = docuemt!.write(to: URL(fileURLWithPath: path), withOptions: options)
  337. if result {
  338. KMPrint("成功")
  339. self.itemSuccess(item: item)
  340. } else {
  341. KMPrint("失败")
  342. self.itemFailure(item: item, error: nil)
  343. }
  344. if i == filesData.count - 1 {
  345. self.batchSuccess()
  346. NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: outputFolderPath)])
  347. }
  348. }
  349. }
  350. }
  351. }
  352. //MARK: 水印
  353. func waterMarkApplay(data: KMBatchSettingItemViewModel, outputFolderPath: String) {
  354. if let data = data as? KMBatchWatermarkModel {
  355. self.waterMarkFile(outputFolderPath: outputFolderPath, data: data, filesData: self.batchFilesData)
  356. }
  357. }
  358. func waterMarkFile(outputFolderPath: String, data: KMBatchWatermarkModel, filesData: [KMBatchProcessingTableViewModel]) {
  359. if filesData.count != 0 {
  360. for i in 0..<filesData.count {
  361. let item = filesData[i]
  362. var path = self.fetchFilePath(type: .watermark, filePath: item.filePath, outputFolderPath: outputFolderPath)
  363. let document = CPDFDocument.init(url: URL(fileURLWithPath: item.filePath))
  364. if (document?.allowsPrinting == false || document?.allowsCopying == false) {
  365. let alert = NSAlert()
  366. alert.alertStyle = .critical
  367. alert.messageText = "此文档不允许修改"
  368. alert.runModal()
  369. return
  370. }
  371. if let watermarks = document?.watermarks(), let model = data.watermarkModel, let document = document {
  372. let pageString = self.fetchValidPageIndexString(document, model: item)
  373. let watermark = KMPDFWatermarkData.returnWaterMarkWith(model, document)
  374. watermark.pageString = pageString
  375. document.addWatermark(watermark)
  376. }
  377. if (FileManager.default.fileExists(atPath: path)) {
  378. try?FileManager.default.removeItem(atPath: path)
  379. }
  380. let result = document?.write(to: URL(fileURLWithPath: path)) ?? false
  381. if (result) {
  382. KMPrint("removeFile成功")
  383. self.itemSuccess(item: item)
  384. } else {
  385. KMPrint("removeFile失败")
  386. self.itemFailure(item: item, error: nil)
  387. }
  388. if i == filesData.count - 1 {
  389. self.batchSuccess()
  390. }
  391. NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: path)])
  392. }
  393. }
  394. }
  395. //MARK: 背景
  396. func backgroundApplay(data: KMBatchSettingItemViewModel, outputFolderPath: String) {
  397. if let data = data as? KMBatchBackgroundModel {
  398. self.backgroundFile(outputFolderPath: outputFolderPath, data: data, filesData: self.batchFilesData)
  399. }
  400. }
  401. func backgroundFile(outputFolderPath: String, data: KMBatchBackgroundModel, filesData: [KMBatchProcessingTableViewModel]) {
  402. if filesData.count != 0 {
  403. for i in 0..<filesData.count {
  404. let item = filesData[i]
  405. var path = self.fetchFilePath(type: .background, filePath: item.filePath, outputFolderPath: outputFolderPath)
  406. let document = CPDFDocument.init(url: URL(fileURLWithPath: item.filePath))
  407. if (document?.allowsPrinting == false || document?.allowsCopying == false) {
  408. let alert = NSAlert()
  409. alert.alertStyle = .critical
  410. alert.messageText = "此文档不允许修改"
  411. alert.runModal()
  412. return
  413. }
  414. if let background = document?.background(), let model = data.backgroundModel, let document = document {
  415. KMBackgroundManager.defaultManager.updateBackground(background, withModel: model)
  416. let pageIndexString = self.fetchValidPageIndexString(document, model: item)
  417. background.pageString = pageIndexString
  418. background.update()
  419. }
  420. if (FileManager.default.fileExists(atPath: path)) {
  421. try?FileManager.default.removeItem(atPath: path)
  422. }
  423. let result = document?.write(to: URL(fileURLWithPath: path)) ?? false
  424. if (result) {
  425. KMPrint("removeFile成功")
  426. self.itemSuccess(item: item)
  427. } else {
  428. KMPrint("removeFile失败")
  429. self.itemFailure(item: item, error: nil)
  430. }
  431. if i == filesData.count - 1 {
  432. self.batchSuccess()
  433. }
  434. NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: path)])
  435. }
  436. }
  437. }
  438. //MARK: 页眉页脚
  439. func headAndFooterApplay(data: KMBatchSettingItemViewModel, outputFolderPath: String) {
  440. if let data = data as? KMBatchHeaderAndFooterModel {
  441. self.headAndFooterFile(outputFolderPath: outputFolderPath, data: data, filesData: self.batchFilesData)
  442. }
  443. }
  444. func headAndFooterFile(outputFolderPath: String, data: KMBatchHeaderAndFooterModel, filesData: [KMBatchProcessingTableViewModel]) {
  445. if filesData.count != 0 {
  446. for i in 0..<filesData.count {
  447. let item = filesData[i]
  448. var path = self.fetchFilePath(type: .headerAndFooter, filePath: item.filePath, outputFolderPath: outputFolderPath)
  449. let document = CPDFDocument.init(url: URL(fileURLWithPath: item.filePath))
  450. if (document?.allowsPrinting == false || document?.allowsCopying == false) {
  451. let alert = NSAlert()
  452. alert.alertStyle = .critical
  453. alert.messageText = "此文档不允许修改"
  454. alert.runModal()
  455. return
  456. }
  457. if let headerFooter = document?.headerFooter(), let model = data.headerFooterModel, let document = document {
  458. let pageString = self.fetchValidPageIndexString(document, model: item)
  459. KMHeaderFooterManager.defaultManager.updateCPDFHeaderFooter(headerFooter, withModel: model, Int(document.pageCount))
  460. headerFooter.pageString = pageString
  461. headerFooter.update()
  462. }
  463. if (FileManager.default.fileExists(atPath: path)) {
  464. try?FileManager.default.removeItem(atPath: path)
  465. }
  466. let result = document?.write(to: URL(fileURLWithPath: path)) ?? false
  467. if (result) {
  468. KMPrint("removeFile成功")
  469. self.itemSuccess(item: item)
  470. } else {
  471. KMPrint("removeFile失败")
  472. self.itemFailure(item: item, error: nil)
  473. }
  474. if i == filesData.count - 1 {
  475. self.batchSuccess()
  476. }
  477. NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: path)])
  478. }
  479. }
  480. }
  481. //MARK: 贝茨码
  482. func batesApplay(data: KMBatchSettingItemViewModel, outputFolderPath: String) {
  483. if let data = data as? KMBatchBatesModel {
  484. self.batesFile(outputFolderPath: outputFolderPath, data: data, filesData: self.batchFilesData)
  485. }
  486. }
  487. func batesFile(outputFolderPath: String, data: KMBatchBatesModel, filesData: [KMBatchProcessingTableViewModel]) {
  488. if filesData.count != 0 {
  489. for i in 0..<filesData.count {
  490. let item = filesData[i]
  491. var path = self.fetchFilePath(type: .batesNumber, filePath: item.filePath, outputFolderPath: outputFolderPath)
  492. let document = CPDFDocument.init(url: URL(fileURLWithPath: item.filePath))
  493. if (document?.allowsPrinting == false || document?.allowsCopying == false) {
  494. let alert = NSAlert()
  495. alert.alertStyle = .critical
  496. alert.messageText = "此文档不允许修改"
  497. alert.runModal()
  498. return
  499. }
  500. if let bates = document?.bates(), let model = data.batesModel, let document = document {
  501. let pageString = self.fetchValidPageIndexString(document, model: item)
  502. KMBatesManager.defaultManager.updateCPDFBates(bates, withModel: model, Int(document.pageCount))
  503. bates.pageString = pageString
  504. bates.update()
  505. }
  506. if (FileManager.default.fileExists(atPath: path)) {
  507. try?FileManager.default.removeItem(atPath: path)
  508. }
  509. let result = document?.write(to: URL(fileURLWithPath: path)) ?? false
  510. if (result) {
  511. KMPrint("removeFile成功")
  512. self.itemSuccess(item: item)
  513. } else {
  514. KMPrint("removeFile失败")
  515. self.itemFailure(item: item, error: nil)
  516. }
  517. if i == filesData.count - 1 {
  518. self.batchSuccess()
  519. }
  520. NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: path)])
  521. }
  522. }
  523. }
  524. //MARK: 移除
  525. func removeApplay(data: KMBatchSettingItemViewModel, outputFolderPath: String) {
  526. self.removeFile(outputFolderPath: outputFolderPath, data: data as! KMBatchRemoveViewModel, filesData: self.batchFilesData)
  527. }
  528. func removeFile(outputFolderPath: String, data: KMBatchRemoveViewModel, filesData: [KMBatchProcessingTableViewModel]) {
  529. if filesData.count != 0 {
  530. for i in 0..<filesData.count {
  531. let item = filesData[i]
  532. // DispatchQueue.global().async {
  533. var path = self.fetchFilePath(type: .batchRemove, filePath: item.filePath, outputFolderPath: outputFolderPath)
  534. let document = CPDFDocument.init(url: URL(fileURLWithPath: item.filePath))
  535. if document != nil {
  536. if (document!.allowsPrinting == false || document!.allowsCopying == false) {
  537. let alert = NSAlert()
  538. alert.alertStyle = .critical
  539. alert.messageText = "此文档不允许修改"
  540. alert.runModal()
  541. return
  542. }
  543. if (data.options.contains(.security)) {
  544. }
  545. if (data.options.contains(.batesNumber)) {
  546. let property = document!.bates()
  547. property?.clear()
  548. }
  549. if (data.options.contains(.headerAndFooter)) {
  550. let property = document!.headerFooter()
  551. property?.clear()
  552. }
  553. if (data.options.contains(.background)) {
  554. let property = document!.background()
  555. property?.clear()
  556. }
  557. if (data.options.contains(.watermark)) {
  558. let array: Array<CPDFWatermark> = document!.watermarks() ?? []
  559. for model in array {
  560. document!.removeWatermark(model)
  561. }
  562. }
  563. if (FileManager.default.fileExists(atPath: path)) {
  564. try?FileManager.default.removeItem(atPath: path)
  565. }
  566. let result = document!.write(to: URL(fileURLWithPath: path))
  567. if (result) {
  568. KMPrint("removeFile成功")
  569. self.itemSuccess(item: item)
  570. } else {
  571. KMPrint("removeFile失败")
  572. self.itemFailure(item: item, error: nil)
  573. }
  574. if i == filesData.count - 1 {
  575. self.batchSuccess()
  576. }
  577. NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: outputFolderPath)])
  578. }
  579. // }
  580. }
  581. }
  582. }
  583. //MARK: 图片转PDF
  584. func imageToPDFExport(data: KMBatchSettingItemViewModel, outputFolderPath: String) {
  585. self.imageToPDFFile(outputFolderPath: outputFolderPath, data: data as! KMBatchImageToPDFModel, filesData: self.batchFilesData)
  586. }
  587. func imageToPDFFile(outputFolderPath: String, data: KMBatchImageToPDFModel, filesData: [KMBatchProcessingTableViewModel]) {
  588. if filesData.count != 0 {
  589. self.batchProgress()
  590. if data.isNewPDF {
  591. if data.isMergeAll {
  592. let item = filesData[0]
  593. var path = self.fetchFilePath(type: .imageToPDF, filePath: item.filePath, outputFolderPath: outputFolderPath)
  594. var pdfDocument = CPDFDocument()
  595. for item in filesData {
  596. pdfDocument?.km_insert(image: item.image, at: pdfDocument?.pageCount ?? 0)
  597. }
  598. if data.isOCR {
  599. let model = KMOCRModel()
  600. model.showType = .page
  601. model.saveAsPDF = true
  602. model.ocrType = data.ocrType
  603. model.languageType = data.languageType
  604. model.needTxT = data.isExtractText
  605. model.pageRangeType = .all
  606. //计算需要处理的页面
  607. let pages:[Int] = KMOCRManager.fetchPageIndex(document: pdfDocument!, model: model)
  608. model.pageRange = pages
  609. self.batchProgress()
  610. self.convertOCR(outputFolderPath: outputFolderPath, document: pdfDocument!, fileName: path.deletingPathExtension.lastPathComponent, data: model) { progress in
  611. self.batchProgress()
  612. } complete: { document, text, error in
  613. self.batchSuccess()
  614. }
  615. } else {
  616. let success = pdfDocument?.write(toFile: path)
  617. if success != nil {
  618. for item in filesData {
  619. self.itemSuccess(item: item)
  620. }
  621. self.batchSuccess()
  622. } else {
  623. self.batchFailure()
  624. }
  625. }
  626. } else {
  627. processFile(at: 0, outputFolderPath: outputFolderPath, data: data)
  628. }
  629. } else {
  630. var fileName = data.selectFilePath.deletingPathExtension.lastPathComponent
  631. let path = self.fetchFilePath(type: .imageToPDF, filePath: data.selectFilePath, outputFolderPath: outputFolderPath)
  632. var pdfDocument = CPDFDocument(url: NSURL(fileURLWithPath: data.selectFilePath) as URL)
  633. let count: Int = Int(pdfDocument?.pageCount ?? 0)
  634. for item in filesData {
  635. pdfDocument?.km_insert(image: item.image, at: pdfDocument?.pageCount ?? 0)
  636. }
  637. if data.isOCR {
  638. let model = KMOCRModel()
  639. model.showType = .page
  640. model.saveAsPDF = true
  641. model.ocrType = data.ocrType
  642. model.languageType = data.languageType
  643. model.needTxT = data.isExtractText
  644. model.pageRangeType = .all
  645. //计算需要处理的页面
  646. let pages:[Int] = KMOCRManager.fetchPageIndex(document: pdfDocument!, model: model)
  647. model.pageRange = pages
  648. self.convertOCR(outputFolderPath: outputFolderPath, document: pdfDocument!, fileName: fileName, data: model) { progress in
  649. } complete: { document, text, error in
  650. if (error != nil) {
  651. self.batchFailure()
  652. } else {
  653. for item in filesData {
  654. self.itemSuccess(item: item)
  655. }
  656. self.batchSuccess()
  657. }
  658. }
  659. } else {
  660. let success = pdfDocument?.write(toFile: path)
  661. if success != nil {
  662. for item in filesData {
  663. self.itemSuccess(item: item)
  664. }
  665. self.batchSuccess()
  666. } else {
  667. self.batchFailure()
  668. }
  669. }
  670. }
  671. }
  672. }
  673. func processFile(at index: Int, outputFolderPath: String, data: KMBatchImageToPDFModel) {
  674. guard index < filesData.count else {
  675. self.batchSuccess()
  676. return
  677. }
  678. let item = filesData[index]
  679. if data.isOCR {
  680. let path = self.fetchFilePath(type: .imageToPDF, filePath: item.filePath, outputFolderPath: outputFolderPath)
  681. let pdfDocument = CPDFDocument()
  682. pdfDocument?.km_insert(image: item.image, at: pdfDocument?.pageCount ?? 0)
  683. let model = KMOCRModel()
  684. model.showType = .page
  685. model.saveAsPDF = true
  686. model.ocrType = data.ocrType
  687. model.languageType = data.languageType
  688. model.needTxT = data.isExtractText
  689. model.pageRangeType = .all
  690. let pages: [Int] = KMOCRManager.fetchPageIndex(document: pdfDocument!, model: model)
  691. model.pageRange = pages
  692. self.itemProgress(item: item, processValue: 0)
  693. self.convertOCR(outputFolderPath: outputFolderPath, document: pdfDocument!, fileName: path.deletingPathExtension.lastPathComponent, data: model) { [unowned self] progress in
  694. self.itemProgress(item: item, processValue: progress)
  695. } complete: { [unowned self] document, text, error in
  696. self.itemSuccess(item: filesData[index])
  697. processFile(at: index + 1, outputFolderPath: outputFolderPath, data: data)
  698. }
  699. } else {
  700. let path = self.fetchFilePath(type: .imageToPDF, filePath: item.filePath, outputFolderPath: outputFolderPath)
  701. let pdfDocument = CPDFDocument()
  702. pdfDocument?.km_insert(image: item.image, at: pdfDocument?.pageCount ?? 0)
  703. let success = pdfDocument?.write(toFile: path)
  704. if success != nil {
  705. self.itemSuccess(item: item)
  706. processFile(at: index + 1, outputFolderPath: outputFolderPath, data: data)
  707. } else {
  708. self.itemFailure(item: item, error: nil)
  709. }
  710. }
  711. }
  712. }
  713. //MARK: private
  714. extension KMBatchManager {
  715. func fetchValidPageIndexString(_ document: CPDFDocument, model: KMBatchProcessingTableViewModel) -> String? {
  716. if model.pageRange == .all {
  717. let pages = Array(0..<Int(document.pageCount))
  718. let pageIndexString = pages.isEmpty ? "" : pages.map { "\($0)" }.joined(separator: ",")
  719. return pageIndexString
  720. } else {
  721. let data = KMOCRModel()
  722. data.pageRangeType = model.pageRange
  723. data.pageRangeString = model.pageRangeString
  724. let pages:[Int] = KMOCRManager.fetchPageIndex(document: document, model: data)
  725. let pageIndexString = pages.isEmpty ? "" : pages.map { "\($0)" }.joined(separator: ",")
  726. return pageIndexString
  727. }
  728. return nil
  729. }
  730. func fetchDocument(filePath: String, model: KMBatchProcessingTableViewModel) -> CPDFDocument {
  731. var document = CPDFDocument(url: URL(fileURLWithPath: filePath))
  732. if model.pageRange == .all {
  733. } else {
  734. let data = KMOCRModel()
  735. data.pageRangeType = model.pageRange
  736. data.pageRangeString = model.pageRangeString
  737. let pages:[Int] = KMOCRManager.fetchPageIndex(document: document!, model: data)
  738. var tempDocument = CPDFDocument()
  739. for i in 0..<pages.count {
  740. let page = document?.page(at: UInt(i))
  741. tempDocument?.insertPageObject(page, at: tempDocument?.pageCount ?? 0)
  742. }
  743. let fileName = filePath.deletingPathExtension.lastPathComponent
  744. let isSuccess = tempDocument?.write(toFile: self.fetchTempFilePath(fileName: fileName))
  745. if isSuccess != nil {
  746. document = tempDocument
  747. }
  748. }
  749. return document ?? CPDFDocument()
  750. }
  751. func fetchTempFilePath(fileName: String) -> String {
  752. let floderPath = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.applicationSupportDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).last?.stringByAppendingPathComponent(Bundle.main.bundleIdentifier!).stringByAppendingPathComponent("BatchTemp")
  753. let filePath = floderPath?.stringByAppendingPathComponent("\(fileName).pdf")
  754. if let data = floderPath, !FileManager.default.fileExists(atPath: data) {
  755. try?FileManager.default.createDirectory(atPath: data, withIntermediateDirectories: false)
  756. }
  757. if let data = filePath, !FileManager.default.fileExists(atPath: data) {
  758. FileManager.default.createFile(atPath: data, contents: nil)
  759. }
  760. return filePath ?? ""
  761. }
  762. func removeTempFilePath(filePath: String) {
  763. let fileName = filePath.deletingPathExtension.lastPathComponent
  764. let path = self.fetchTempFilePath(fileName: fileName)
  765. if (FileManager.default.fileExists(atPath: path)) {
  766. try?FileManager.default.removeItem(atPath: path)
  767. }
  768. }
  769. func fetchFilePath(type: KMBatchCollectionViewType, filePath: String, outputFolderPath: String) -> String {
  770. var fileName = filePath.deletingPathExtension.lastPathComponent
  771. if fileName.isEmpty {
  772. fileName = NSLocalizedString("Untitled", comment: "")
  773. }
  774. var path = outputFolderPath + "/" + fileName + ".pdf"
  775. // // 检查文件是否已存在,如果存在,则添加数字后缀
  776. // var finalPath = path
  777. // var count = 1
  778. // while FileManager.default.fileExists(atPath: finalPath) {
  779. // let newFileName = "\(fileName) \(count)"
  780. // finalPath = outputFolderPath + "/" + newFileName + ".pdf"
  781. // count += 1
  782. // }
  783. // 使用最终路径进行保存或其他操作
  784. // path = finalPath
  785. return path
  786. }
  787. }
  788. //MARK: Alert
  789. extension KMBatchManager {
  790. func batchUnkown() {
  791. self.state = .unknow
  792. NotificationCenter.default.post(name: NSNotification.Name(kBacthProcessNotification), object: nil)
  793. }
  794. func batchProgress() {
  795. for item in filesData {
  796. self.itemProgress(item: item, processValue: 0)
  797. }
  798. self.state = .processing
  799. NotificationCenter.default.post(name: NSNotification.Name(kBacthProcessNotification), object: nil)
  800. }
  801. func batchSuccess() {
  802. self.state = .complete
  803. NotificationCenter.default.post(name: NSNotification.Name(kBacthProcessNotification), object: nil)
  804. }
  805. func batchFailure() {
  806. self.state = .error
  807. NotificationCenter.default.post(name: NSNotification.Name(kBacthProcessNotification), object: nil)
  808. }
  809. func itemProgress(item: KMBatchProcessingTableViewModel, processValue: Float) {
  810. if processValue > 0.7 {
  811. item.state = .loading70
  812. } else {
  813. item.state = .loading
  814. }
  815. NotificationCenter.default.post(name: NSNotification.Name(kBacthFilesProcessNotification), object: item)
  816. }
  817. func itemSuccess(item: KMBatchProcessingTableViewModel) {
  818. self.removeTempFilePath(filePath: item.filePath)
  819. item.state = .success
  820. NotificationCenter.default.post(name: NSNotification.Name(kBacthFilesProcessNotification), object: item)
  821. }
  822. func itemFailure(item: KMBatchProcessingTableViewModel, error: NSError?) {
  823. self.removeTempFilePath(filePath: item.filePath)
  824. item.state = .error
  825. NotificationCenter.default.post(name: NSNotification.Name(kBacthFilesProcessNotification), object: item)
  826. guard let error = error else { return }
  827. var errorString = ""
  828. let myError: NSError = error as NSError
  829. if myError.code == 1 {
  830. errorString = NSLocalizedString("Password required or incorrect password. Please re-enter your password and try again", comment: "")
  831. } else if myError.code == 2 {
  832. errorString = NSLocalizedString("The license doesn't allow the permission", comment: "")
  833. } else if myError.code == 3 {
  834. errorString = NSLocalizedString("Malloc failure", comment: "")
  835. } else if myError.code == 4 {
  836. errorString = NSLocalizedString("Unknown error in processing conversion. Please try again later", comment: "")
  837. } else if myError.code == 5 {
  838. errorString = NSLocalizedString("Unknown error in processing PDF. Please try again later", comment: "")
  839. } else if myError.code == 6 {
  840. errorString = NSLocalizedString("File not found or could not be opened. Check if your file exists or choose another file to convert", comment: "")
  841. } else if myError.code == 7 {
  842. errorString = NSLocalizedString("File not in PDF format or corruptead. Change a PDF file and try again", comment: "")
  843. } else if myError.code == 8 {
  844. errorString = NSLocalizedString("Unsupported security scheme", comment: "")
  845. } else if myError.code == 9 {
  846. errorString = NSLocalizedString("Page not found or content error", comment: "")
  847. } else {
  848. errorString = NSLocalizedString("Table not found", comment: "")
  849. }
  850. let alert = NSAlert()
  851. alert.alertStyle = .critical
  852. alert.messageText = NSLocalizedString("Conversion Failed", comment: "")
  853. alert.informativeText = errorString
  854. alert.addButton(withTitle: NSLocalizedString("OK", comment: ""))
  855. alert.runModal()
  856. }
  857. }