KMBatchManager.swift 42 KB

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