KMBatchManager.swift 43 KB

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