KMBatchManager.swift 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021
  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. let 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. let path = self.fetchFilePath(type: .OCR, filePath: item.filePath, outputFolderPath: outputFolderPath)
  240. data.pageRange = self.fetchValidPageIndexs(document!, model: item) ?? []
  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. let 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. let 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. }
  347. }
  348. }
  349. }
  350. }
  351. //MARK: 水印
  352. func waterMarkApplay(data: KMBatchSettingItemViewModel, outputFolderPath: String) {
  353. if let data = data as? KMBatchWatermarkModel {
  354. self.waterMarkFile(outputFolderPath: outputFolderPath, data: data, filesData: self.batchFilesData)
  355. }
  356. }
  357. func waterMarkFile(outputFolderPath: String, data: KMBatchWatermarkModel, filesData: [KMBatchProcessingTableViewModel]) {
  358. if filesData.count != 0 {
  359. for i in 0..<filesData.count {
  360. let item = filesData[i]
  361. let path = self.fetchFilePath(type: .watermark, filePath: item.filePath, outputFolderPath: outputFolderPath)
  362. let document = CPDFDocument.init(url: URL(fileURLWithPath: item.filePath))
  363. if (document?.allowsPrinting == false || document?.allowsCopying == false) {
  364. let alert = NSAlert()
  365. alert.alertStyle = .critical
  366. alert.messageText = "此文档不允许修改"
  367. alert.runModal()
  368. return
  369. }
  370. if let watermarks = document?.watermarks(), let model = data.watermarkModel, let document = document {
  371. let pageString = self.fetchValidPageIndexString(document, model: item)
  372. let watermark = KMWatermarkModel.returnWaterMarkWith(model, document)
  373. watermark.pageString = pageString
  374. document.addWatermark(watermark)
  375. }
  376. if (FileManager.default.fileExists(atPath: path)) {
  377. try?FileManager.default.removeItem(atPath: path)
  378. }
  379. let result = document?.write(to: URL(fileURLWithPath: path)) ?? false
  380. if (result) {
  381. KMPrint("removeFile成功")
  382. self.itemSuccess(item: item)
  383. } else {
  384. KMPrint("removeFile失败")
  385. self.itemFailure(item: item, error: nil)
  386. }
  387. if i == filesData.count - 1 {
  388. self.batchSuccess()
  389. }
  390. }
  391. }
  392. }
  393. //MARK: 背景
  394. func backgroundApplay(data: KMBatchSettingItemViewModel, outputFolderPath: String) {
  395. if let data = data as? KMBatchBackgroundModel {
  396. self.backgroundFile(outputFolderPath: outputFolderPath, data: data, filesData: self.batchFilesData)
  397. }
  398. }
  399. func backgroundFile(outputFolderPath: String, data: KMBatchBackgroundModel, filesData: [KMBatchProcessingTableViewModel]) {
  400. if filesData.count != 0 {
  401. for i in 0..<filesData.count {
  402. let item = filesData[i]
  403. let path = self.fetchFilePath(type: .background, filePath: item.filePath, outputFolderPath: outputFolderPath)
  404. let document = CPDFDocument.init(url: URL(fileURLWithPath: item.filePath))
  405. if (document?.allowsPrinting == false || document?.allowsCopying == false) {
  406. let alert = NSAlert()
  407. alert.alertStyle = .critical
  408. alert.messageText = "此文档不允许修改"
  409. alert.runModal()
  410. return
  411. }
  412. if let background = document?.background(), let model = data.backgroundModel, let document = document {
  413. KMBackgroundManager.defaultManager.updateBackground(background, withModel: model)
  414. let pageIndexString = self.fetchValidPageIndexString(document, model: item)
  415. background.pageString = pageIndexString
  416. background.update()
  417. }
  418. if (FileManager.default.fileExists(atPath: path)) {
  419. try?FileManager.default.removeItem(atPath: path)
  420. }
  421. let result = document?.write(to: URL(fileURLWithPath: path)) ?? false
  422. if (result) {
  423. KMPrint("removeFile成功")
  424. self.itemSuccess(item: item)
  425. } else {
  426. KMPrint("removeFile失败")
  427. self.itemFailure(item: item, error: nil)
  428. }
  429. if i == filesData.count - 1 {
  430. self.batchSuccess()
  431. }
  432. }
  433. }
  434. }
  435. //MARK: 页眉页脚
  436. func headAndFooterApplay(data: KMBatchSettingItemViewModel, outputFolderPath: String) {
  437. if let data = data as? KMBatchHeaderAndFooterModel {
  438. self.headAndFooterFile(outputFolderPath: outputFolderPath, data: data, filesData: self.batchFilesData)
  439. }
  440. }
  441. func headAndFooterFile(outputFolderPath: String, data: KMBatchHeaderAndFooterModel, filesData: [KMBatchProcessingTableViewModel]) {
  442. if filesData.count != 0 {
  443. for i in 0..<filesData.count {
  444. let item = filesData[i]
  445. let path = self.fetchFilePath(type: .headerAndFooter, filePath: item.filePath, outputFolderPath: outputFolderPath)
  446. let document = CPDFDocument.init(url: URL(fileURLWithPath: item.filePath))
  447. if (document?.allowsPrinting == false || document?.allowsCopying == false) {
  448. let alert = NSAlert()
  449. alert.alertStyle = .critical
  450. alert.messageText = "此文档不允许修改"
  451. alert.runModal()
  452. return
  453. }
  454. if let headerFooter = document?.headerFooter(), let model = data.headerFooterModel, let document = document {
  455. let pageString = self.fetchValidPageIndexString(document, model: item)
  456. KMHeaderFooterManager.defaultManager.updateCPDFHeaderFooter(headerFooter, withModel: model, Int(document.pageCount))
  457. headerFooter.pageString = pageString
  458. headerFooter.update()
  459. }
  460. if (FileManager.default.fileExists(atPath: path)) {
  461. try?FileManager.default.removeItem(atPath: path)
  462. }
  463. let result = document?.write(to: URL(fileURLWithPath: path)) ?? false
  464. if (result) {
  465. KMPrint("removeFile成功")
  466. self.itemSuccess(item: item)
  467. } else {
  468. KMPrint("removeFile失败")
  469. self.itemFailure(item: item, error: nil)
  470. }
  471. if i == filesData.count - 1 {
  472. self.batchSuccess()
  473. }
  474. }
  475. }
  476. }
  477. //MARK: 贝茨码
  478. func batesApplay(data: KMBatchSettingItemViewModel, outputFolderPath: String) {
  479. if let data = data as? KMBatchBatesModel {
  480. self.batesFile(outputFolderPath: outputFolderPath, data: data, filesData: self.batchFilesData)
  481. }
  482. }
  483. func batesFile(outputFolderPath: String, data: KMBatchBatesModel, filesData: [KMBatchProcessingTableViewModel]) {
  484. if filesData.count != 0 {
  485. for i in 0..<filesData.count {
  486. let item = filesData[i]
  487. let path = self.fetchFilePath(type: .batesNumber, filePath: item.filePath, outputFolderPath: outputFolderPath)
  488. let document = CPDFDocument.init(url: URL(fileURLWithPath: item.filePath))
  489. if (document?.allowsPrinting == false || document?.allowsCopying == false) {
  490. let alert = NSAlert()
  491. alert.alertStyle = .critical
  492. alert.messageText = "此文档不允许修改"
  493. alert.runModal()
  494. return
  495. }
  496. if let bates = document?.bates(), let model = data.batesModel, let document = document {
  497. let pageString = self.fetchValidPageIndexString(document, model: item)
  498. KMBatesManager.defaultManager.updateCPDFBates(bates, withModel: model, Int(document.pageCount))
  499. bates.pageString = pageString
  500. bates.update()
  501. }
  502. if (FileManager.default.fileExists(atPath: path)) {
  503. try?FileManager.default.removeItem(atPath: path)
  504. }
  505. let result = document?.write(to: URL(fileURLWithPath: path)) ?? false
  506. if (result) {
  507. KMPrint("removeFile成功")
  508. self.itemSuccess(item: item)
  509. } else {
  510. KMPrint("removeFile失败")
  511. self.itemFailure(item: item, error: nil)
  512. }
  513. if i == filesData.count - 1 {
  514. self.batchSuccess()
  515. }
  516. }
  517. }
  518. }
  519. //MARK: 移除
  520. func removeApplay(data: KMBatchSettingItemViewModel, outputFolderPath: String) {
  521. self.removeFile(outputFolderPath: outputFolderPath, data: data as! KMBatchRemoveViewModel, filesData: self.batchFilesData)
  522. }
  523. func removeFile(outputFolderPath: String, data: KMBatchRemoveViewModel, filesData: [KMBatchProcessingTableViewModel]) {
  524. if filesData.count != 0 {
  525. for i in 0..<filesData.count {
  526. let item = filesData[i]
  527. // DispatchQueue.global().async {
  528. let path = self.fetchFilePath(type: .batchRemove, filePath: item.filePath, outputFolderPath: outputFolderPath)
  529. let document = CPDFDocument.init(url: URL(fileURLWithPath: item.filePath))
  530. if document != nil {
  531. if (document!.allowsPrinting == false || document!.allowsCopying == false) {
  532. let alert = NSAlert()
  533. alert.alertStyle = .critical
  534. alert.messageText = "此文档不允许修改"
  535. alert.runModal()
  536. return
  537. }
  538. if (data.options.contains(.security)) {
  539. }
  540. if (data.options.contains(.batesNumber)) {
  541. let property = document!.bates()
  542. property?.clear()
  543. }
  544. if (data.options.contains(.headerAndFooter)) {
  545. let property = document!.headerFooter()
  546. property?.clear()
  547. }
  548. if (data.options.contains(.background)) {
  549. let property = document!.background()
  550. property?.clear()
  551. }
  552. if (data.options.contains(.watermark)) {
  553. let array: Array<CPDFWatermark> = document!.watermarks() ?? []
  554. for model in array {
  555. document!.removeWatermark(model)
  556. }
  557. }
  558. if (FileManager.default.fileExists(atPath: path)) {
  559. try?FileManager.default.removeItem(atPath: path)
  560. }
  561. let result = document!.write(to: URL(fileURLWithPath: path))
  562. if (result) {
  563. KMPrint("removeFile成功")
  564. self.itemSuccess(item: item)
  565. } else {
  566. KMPrint("removeFile失败")
  567. self.itemFailure(item: item, error: nil)
  568. }
  569. if i == filesData.count - 1 {
  570. self.batchSuccess()
  571. }
  572. }
  573. // }
  574. }
  575. }
  576. }
  577. //MARK: 图片转PDF
  578. func imageToPDFExport(data: KMBatchSettingItemViewModel, outputFolderPath: String) {
  579. self.imageToPDFFile(outputFolderPath: outputFolderPath, data: data as! KMBatchImageToPDFModel, filesData: self.batchFilesData)
  580. }
  581. func imageToPDFFile(outputFolderPath: String, data: KMBatchImageToPDFModel, filesData: [KMBatchProcessingTableViewModel]) {
  582. if filesData.count != 0 {
  583. self.batchProgress()
  584. if data.isNewPDF {
  585. if data.isMergeAll {
  586. let item = filesData[0]
  587. let path = self.fetchFilePath(type: .imageToPDF, filePath: item.filePath, outputFolderPath: outputFolderPath)
  588. let pdfDocument = CPDFDocument()
  589. for item in filesData {
  590. pdfDocument?.km_insert(image: item.image, at: pdfDocument?.pageCount ?? 0)
  591. }
  592. if data.isOCR {
  593. let model = KMOCRModel()
  594. model.showType = .page
  595. model.saveAsPDF = true
  596. model.ocrType = data.ocrType
  597. model.languageType = data.languageType
  598. model.needTxT = data.isExtractText
  599. model.pageRangeType = .all
  600. //计算需要处理的页面
  601. let pages:[Int] = KMOCRManager.fetchPageIndex(document: pdfDocument!, model: model)
  602. model.pageRange = pages
  603. self.batchProgress()
  604. self.convertOCR(outputFolderPath: outputFolderPath, document: pdfDocument!, fileName: path.deletingPathExtension.lastPathComponent, data: model) { progress in
  605. self.batchProgress()
  606. } complete: { document, text, error in
  607. self.batchSuccess()
  608. }
  609. } else {
  610. let success = pdfDocument?.write(toFile: path)
  611. if success != nil {
  612. for item in filesData {
  613. self.itemSuccess(item: item)
  614. }
  615. self.batchSuccess()
  616. } else {
  617. self.batchFailure()
  618. }
  619. }
  620. } else {
  621. processFile(at: 0, outputFolderPath: outputFolderPath, data: data)
  622. }
  623. } else {
  624. let selectFilePath = data.selectFilePath
  625. if selectFilePath.count == 0 {
  626. let alert = NSAlert()
  627. alert.alertStyle = .critical
  628. alert.messageText = KMLocalizedString("文件未选择")
  629. alert.runModal()
  630. return
  631. }
  632. var fileName = selectFilePath.deletingPathExtension.lastPathComponent
  633. let path = self.fetchFilePath(type: .imageToPDF, filePath: selectFilePath, outputFolderPath: outputFolderPath)
  634. var pdfDocument = CPDFDocument(url: NSURL(fileURLWithPath: selectFilePath) as URL)
  635. let count: Int = Int(pdfDocument?.pageCount ?? 0)
  636. for item in filesData {
  637. pdfDocument?.km_insert(image: item.image, at: UInt(count))
  638. }
  639. if data.isOCR {
  640. let model = KMOCRModel()
  641. model.showType = .page
  642. model.saveAsPDF = true
  643. model.ocrType = data.ocrType
  644. model.languageType = data.languageType
  645. model.needTxT = data.isExtractText
  646. model.pageRangeType = .all
  647. //计算需要处理的页面
  648. let pages:[Int] = KMOCRManager.fetchPageIndex(document: pdfDocument!, model: model)
  649. model.pageRange = pages
  650. self.convertOCR(outputFolderPath: outputFolderPath, document: pdfDocument!, fileName: fileName, data: model) { progress in
  651. } complete: { document, text, error in
  652. if (error != nil) {
  653. self.batchFailure()
  654. } else {
  655. for item in filesData {
  656. self.itemSuccess(item: item)
  657. }
  658. self.batchSuccess()
  659. }
  660. }
  661. } else {
  662. let success = pdfDocument?.write(toFile: path)
  663. if success != nil {
  664. for item in filesData {
  665. self.itemSuccess(item: item)
  666. }
  667. self.batchSuccess()
  668. } else {
  669. self.batchFailure()
  670. }
  671. }
  672. }
  673. }
  674. }
  675. func processFile(at index: Int, outputFolderPath: String, data: KMBatchImageToPDFModel) {
  676. guard index < filesData.count else {
  677. self.batchSuccess()
  678. return
  679. }
  680. let item = filesData[index]
  681. if data.isOCR {
  682. let path = self.fetchFilePath(type: .imageToPDF, filePath: item.filePath, outputFolderPath: outputFolderPath)
  683. let pdfDocument = CPDFDocument()
  684. pdfDocument?.km_insert(image: item.image, at: pdfDocument?.pageCount ?? 0)
  685. let model = KMOCRModel()
  686. model.showType = .page
  687. model.saveAsPDF = true
  688. model.ocrType = data.ocrType
  689. model.languageType = data.languageType
  690. model.needTxT = data.isExtractText
  691. model.pageRangeType = .all
  692. let pages: [Int] = KMOCRManager.fetchPageIndex(document: pdfDocument!, model: model)
  693. model.pageRange = pages
  694. self.itemProgress(item: item, processValue: 0)
  695. self.convertOCR(outputFolderPath: outputFolderPath, document: pdfDocument!, fileName: path.deletingPathExtension.lastPathComponent, data: model) { [unowned self] progress in
  696. self.itemProgress(item: item, processValue: progress)
  697. } complete: { [unowned self] document, text, error in
  698. self.itemSuccess(item: filesData[index])
  699. processFile(at: index + 1, outputFolderPath: outputFolderPath, data: data)
  700. }
  701. } else {
  702. let path = self.fetchFilePath(type: .imageToPDF, filePath: item.filePath, outputFolderPath: outputFolderPath)
  703. let pdfDocument = CPDFDocument()
  704. pdfDocument?.km_insert(image: item.image, at: pdfDocument?.pageCount ?? 0)
  705. let success = pdfDocument?.write(toFile: path)
  706. if success != nil {
  707. self.itemSuccess(item: item)
  708. processFile(at: index + 1, outputFolderPath: outputFolderPath, data: data)
  709. } else {
  710. self.itemFailure(item: item, error: nil)
  711. }
  712. }
  713. }
  714. }
  715. //MARK: private
  716. extension KMBatchManager {
  717. func fetchValidPageIndexString(_ document: CPDFDocument, model: KMBatchProcessingTableViewModel) -> String? {
  718. if model.pageRange == .all {
  719. let pages = Array(0..<Int(document.pageCount))
  720. let pageIndexString = pages.isEmpty ? "" : pages.map { "\($0)" }.joined(separator: ",")
  721. return pageIndexString
  722. } else {
  723. let data = KMOCRModel()
  724. data.pageRangeType = model.pageRange
  725. data.pageRangeString = model.pageRangeString
  726. let pages:[Int] = KMOCRManager.fetchPageIndex(document: document, model: data)
  727. let pageIndexString = pages.isEmpty ? "" : pages.map { "\($0)" }.joined(separator: ",")
  728. return pageIndexString
  729. }
  730. return nil
  731. }
  732. func fetchValidPageIndexs(_ document: CPDFDocument, model: KMBatchProcessingTableViewModel) -> [Int]? {
  733. if model.pageRange == .all {
  734. let pages = Array(0..<Int(document.pageCount))
  735. return pages
  736. } else {
  737. let data = KMOCRModel()
  738. data.pageRangeType = model.pageRange
  739. data.pageRangeString = model.pageRangeString
  740. let pages:[Int] = KMOCRManager.fetchPageIndex(document: document, model: data)
  741. return pages
  742. }
  743. return []
  744. }
  745. func fetchDocument(filePath: String, model: KMBatchProcessingTableViewModel) -> CPDFDocument {
  746. var document = CPDFDocument(url: URL(fileURLWithPath: filePath))
  747. if model.password.count != 0 {
  748. document?.unlock(withPassword: model.password)
  749. }
  750. if model.pageRange == .all {
  751. } else {
  752. let data = KMOCRModel()
  753. data.pageRangeType = model.pageRange
  754. data.pageRangeString = model.pageRangeString
  755. let pages:[Int] = KMOCRManager.fetchPageIndex(document: document!, model: data)
  756. var tempDocument = CPDFDocument()
  757. for i in 0..<pages.count {
  758. let page = document?.page(at: UInt(i))
  759. tempDocument?.insertPageObject(page, at: tempDocument?.pageCount ?? 0)
  760. }
  761. let fileName = filePath.deletingPathExtension.lastPathComponent
  762. let isSuccess = tempDocument?.write(toFile: self.fetchTempFilePath(fileName: fileName))
  763. if isSuccess != nil {
  764. document = tempDocument
  765. }
  766. }
  767. return document ?? CPDFDocument()
  768. }
  769. func fetchTempFilePath(fileName: String) -> String {
  770. let floderPath = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.applicationSupportDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).last?.stringByAppendingPathComponent(Bundle.main.bundleIdentifier!).stringByAppendingPathComponent("BatchTemp")
  771. let filePath = floderPath?.stringByAppendingPathComponent("\(fileName).pdf")
  772. if let data = floderPath, !FileManager.default.fileExists(atPath: data) {
  773. try?FileManager.default.createDirectory(atPath: data, withIntermediateDirectories: false)
  774. }
  775. if let data = filePath, !FileManager.default.fileExists(atPath: data) {
  776. FileManager.default.createFile(atPath: data, contents: nil)
  777. }
  778. return filePath ?? ""
  779. }
  780. func removeTempFilePath(filePath: String) {
  781. let fileName = filePath.deletingPathExtension.lastPathComponent
  782. let path = self.fetchTempFilePath(fileName: fileName)
  783. if (FileManager.default.fileExists(atPath: path)) {
  784. try?FileManager.default.removeItem(atPath: path)
  785. }
  786. }
  787. func fetchFilePath(type: KMBatchCollectionViewType, filePath: String, outputFolderPath: String) -> String {
  788. var fileName = filePath.deletingPathExtension.lastPathComponent
  789. if fileName.isEmpty {
  790. fileName = NSLocalizedString("Untitled", comment: "")
  791. }
  792. let path = outputFolderPath + "/" + fileName + ".pdf"
  793. // // 检查文件是否已存在,如果存在,则添加数字后缀
  794. // var finalPath = path
  795. // var count = 1
  796. // while FileManager.default.fileExists(atPath: finalPath) {
  797. // let newFileName = "\(fileName) \(count)"
  798. // finalPath = outputFolderPath + "/" + newFileName + ".pdf"
  799. // count += 1
  800. // }
  801. // 使用最终路径进行保存或其他操作
  802. // path = finalPath
  803. return path
  804. }
  805. }
  806. //MARK: Alert
  807. extension KMBatchManager {
  808. func batchUnkown() {
  809. self.state = .unknow
  810. NotificationCenter.default.post(name: NSNotification.Name(kBacthProcessNotification), object: nil)
  811. }
  812. func batchProgress() {
  813. for item in filesData {
  814. self.itemProgress(item: item, processValue: 0)
  815. }
  816. self.state = .processing
  817. NotificationCenter.default.post(name: NSNotification.Name(kBacthProcessNotification), object: nil)
  818. }
  819. func batchSuccess() {
  820. if FileManager.default.fileExists(atPath: self.outputFolderPath) {
  821. NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: self.outputFolderPath)])
  822. }
  823. self.state = .complete
  824. NotificationCenter.default.post(name: NSNotification.Name(kBacthProcessNotification), object: nil)
  825. }
  826. func batchFailure() {
  827. if FileManager.default.fileExists(atPath: self.outputFolderPath) {
  828. NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: self.outputFolderPath)])
  829. }
  830. self.state = .error
  831. NotificationCenter.default.post(name: NSNotification.Name(kBacthProcessNotification), object: nil)
  832. }
  833. func itemProgress(item: KMBatchProcessingTableViewModel, processValue: Float) {
  834. if processValue > 0.7 {
  835. item.state = .loading70
  836. } else {
  837. item.state = .loading
  838. }
  839. NotificationCenter.default.post(name: NSNotification.Name(kBacthFilesProcessNotification), object: item)
  840. }
  841. func itemSuccess(item: KMBatchProcessingTableViewModel) {
  842. self.removeTempFilePath(filePath: item.filePath)
  843. item.state = .success
  844. NotificationCenter.default.post(name: NSNotification.Name(kBacthFilesProcessNotification), object: item)
  845. }
  846. func itemFailure(item: KMBatchProcessingTableViewModel, error: NSError?) {
  847. self.removeTempFilePath(filePath: item.filePath)
  848. item.state = .error
  849. NotificationCenter.default.post(name: NSNotification.Name(kBacthFilesProcessNotification), object: item)
  850. guard let error = error else { return }
  851. var errorString = ""
  852. let myError: NSError = error as NSError
  853. if myError.code == 1 {
  854. errorString = NSLocalizedString("Password required or incorrect password. Please re-enter your password and try again", comment: "")
  855. } else if myError.code == 2 {
  856. errorString = NSLocalizedString("The license doesn't allow the permission", comment: "")
  857. } else if myError.code == 3 {
  858. errorString = NSLocalizedString("Malloc failure", comment: "")
  859. } else if myError.code == 4 {
  860. errorString = NSLocalizedString("Unknown error in processing conversion. Please try again later", comment: "")
  861. } else if myError.code == 5 {
  862. errorString = NSLocalizedString("Unknown error in processing PDF. Please try again later", comment: "")
  863. } else if myError.code == 6 {
  864. errorString = NSLocalizedString("File not found or could not be opened. Check if your file exists or choose another file to convert", comment: "")
  865. } else if myError.code == 7 {
  866. errorString = NSLocalizedString("File not in PDF format or corruptead. Change a PDF file and try again", comment: "")
  867. } else if myError.code == 8 {
  868. errorString = NSLocalizedString("Unsupported security scheme", comment: "")
  869. } else if myError.code == 9 {
  870. errorString = NSLocalizedString("Page not found or content error", comment: "")
  871. } else if myError.code == 404 {
  872. errorString = NSLocalizedString("Please check if the information is wrong or the network is error.", comment: "")
  873. } else {
  874. errorString = NSLocalizedString("Table not found", comment: "")
  875. }
  876. let alert = NSAlert()
  877. alert.alertStyle = .critical
  878. alert.messageText = NSLocalizedString("Conversion Failed", comment: "")
  879. alert.informativeText = errorString
  880. alert.addButton(withTitle: NSLocalizedString("OK", comment: ""))
  881. alert.runModal()
  882. }
  883. }