KMBatchManager.swift 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999
  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. }
  80. }
  81. //MARK: 批量
  82. extension KMBatchManager {
  83. //MARK: 转档
  84. func convertPDFExport(data: KMBatchSettingItemViewModel, outputFolderPath: String) {
  85. self.convertFile(outputFolderPath: outputFolderPath, data: data, filesData: self.batchFilesData)
  86. }
  87. func convertFile(outputFolderPath: String, data: KMBatchSettingItemViewModel, filesData: [KMBatchProcessingTableViewModel]) {
  88. guard !filesData.isEmpty else { return }
  89. func processFile(at index: Int) {
  90. guard index < filesData.count else {
  91. self.batchSuccess()
  92. return
  93. }
  94. let item = filesData[index]
  95. let filePath = item.filePath
  96. let document = self.fetchDocument(filePath: filePath, model: item)
  97. let settingData = data as? KMBatchConvertPDFViewModel ?? KMBatchConvertPDFViewModel()
  98. var path = self.fetchFilePath(type: .convertPDF, filePath: filePath, outputFolderPath: outputFolderPath)
  99. let convert = self.addConvertParameter(settingData)
  100. let pageCount = document.pageCount
  101. // 获取页面
  102. let pages: [Int] = Array(1...Int(pageCount))
  103. convert.outputFolderPath = outputFolderPath
  104. convert.filePath = filePath
  105. convert.password = item.password
  106. convert.outputFileName = path.deletingPathExtension.lastPathComponent
  107. convert.pages = pages
  108. convert.isAllowOCR = settingData.needRecognizeText
  109. convert.ocrLanguage = settingData.languageType
  110. item.state = .clock
  111. KMPDFConvertManager.defaultManager.convert(convert: convert, progress: { [unowned self] progressValue in
  112. print("转档进度 - \(progressValue)")
  113. let progress = Float(progressValue) / Float(pageCount)
  114. self.itemProgress(item: item, processValue: progress)
  115. }, completion: { [unowned self] finished, error in
  116. if finished {
  117. if FileManager.default.fileExists(atPath: outputFolderPath) {
  118. NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: outputFolderPath)])
  119. }
  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. NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: outputFolderPath)])
  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. var 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. NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: path)])
  391. }
  392. }
  393. }
  394. //MARK: 背景
  395. func backgroundApplay(data: KMBatchSettingItemViewModel, outputFolderPath: String) {
  396. if let data = data as? KMBatchBackgroundModel {
  397. self.backgroundFile(outputFolderPath: outputFolderPath, data: data, filesData: self.batchFilesData)
  398. }
  399. }
  400. func backgroundFile(outputFolderPath: String, data: KMBatchBackgroundModel, filesData: [KMBatchProcessingTableViewModel]) {
  401. if filesData.count != 0 {
  402. for i in 0..<filesData.count {
  403. let item = filesData[i]
  404. var path = self.fetchFilePath(type: .background, filePath: item.filePath, outputFolderPath: outputFolderPath)
  405. let document = CPDFDocument.init(url: URL(fileURLWithPath: item.filePath))
  406. if (document?.allowsPrinting == false || document?.allowsCopying == false) {
  407. let alert = NSAlert()
  408. alert.alertStyle = .critical
  409. alert.messageText = "此文档不允许修改"
  410. alert.runModal()
  411. return
  412. }
  413. if let background = document?.background(), let model = data.backgroundModel, let document = document {
  414. KMBackgroundManager.defaultManager.updateBackground(background, withModel: model)
  415. let pageIndexString = self.fetchValidPageIndexString(document, model: item)
  416. background.pageString = pageIndexString
  417. background.update()
  418. }
  419. if (FileManager.default.fileExists(atPath: path)) {
  420. try?FileManager.default.removeItem(atPath: path)
  421. }
  422. let result = document?.write(to: URL(fileURLWithPath: path)) ?? false
  423. if (result) {
  424. KMPrint("removeFile成功")
  425. self.itemSuccess(item: item)
  426. } else {
  427. KMPrint("removeFile失败")
  428. self.itemFailure(item: item, error: nil)
  429. }
  430. if i == filesData.count - 1 {
  431. self.batchSuccess()
  432. }
  433. NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: path)])
  434. }
  435. }
  436. }
  437. //MARK: 页眉页脚
  438. func headAndFooterApplay(data: KMBatchSettingItemViewModel, outputFolderPath: String) {
  439. if let data = data as? KMBatchHeaderAndFooterModel {
  440. self.headAndFooterFile(outputFolderPath: outputFolderPath, data: data, filesData: self.batchFilesData)
  441. }
  442. }
  443. func headAndFooterFile(outputFolderPath: String, data: KMBatchHeaderAndFooterModel, filesData: [KMBatchProcessingTableViewModel]) {
  444. if filesData.count != 0 {
  445. for i in 0..<filesData.count {
  446. let item = filesData[i]
  447. var path = self.fetchFilePath(type: .headerAndFooter, filePath: item.filePath, outputFolderPath: outputFolderPath)
  448. let document = CPDFDocument.init(url: URL(fileURLWithPath: item.filePath))
  449. if (document?.allowsPrinting == false || document?.allowsCopying == false) {
  450. let alert = NSAlert()
  451. alert.alertStyle = .critical
  452. alert.messageText = "此文档不允许修改"
  453. alert.runModal()
  454. return
  455. }
  456. if let headerFooter = document?.headerFooter(), let model = data.headerFooterModel, let document = document {
  457. let pageString = self.fetchValidPageIndexString(document, model: item)
  458. KMHeaderFooterManager.defaultManager.updateCPDFHeaderFooter(headerFooter, withModel: model, Int(document.pageCount))
  459. headerFooter.pageString = pageString
  460. headerFooter.update()
  461. }
  462. if (FileManager.default.fileExists(atPath: path)) {
  463. try?FileManager.default.removeItem(atPath: path)
  464. }
  465. let result = document?.write(to: URL(fileURLWithPath: path)) ?? false
  466. if (result) {
  467. KMPrint("removeFile成功")
  468. self.itemSuccess(item: item)
  469. } else {
  470. KMPrint("removeFile失败")
  471. self.itemFailure(item: item, error: nil)
  472. }
  473. if i == filesData.count - 1 {
  474. self.batchSuccess()
  475. }
  476. NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: path)])
  477. }
  478. }
  479. }
  480. //MARK: 贝茨码
  481. func batesApplay(data: KMBatchSettingItemViewModel, outputFolderPath: String) {
  482. if let data = data as? KMBatchBatesModel {
  483. self.batesFile(outputFolderPath: outputFolderPath, data: data, filesData: self.batchFilesData)
  484. }
  485. }
  486. func batesFile(outputFolderPath: String, data: KMBatchBatesModel, filesData: [KMBatchProcessingTableViewModel]) {
  487. if filesData.count != 0 {
  488. for i in 0..<filesData.count {
  489. let item = filesData[i]
  490. var path = self.fetchFilePath(type: .batesNumber, filePath: item.filePath, outputFolderPath: outputFolderPath)
  491. let document = CPDFDocument.init(url: URL(fileURLWithPath: item.filePath))
  492. if (document?.allowsPrinting == false || document?.allowsCopying == false) {
  493. let alert = NSAlert()
  494. alert.alertStyle = .critical
  495. alert.messageText = "此文档不允许修改"
  496. alert.runModal()
  497. return
  498. }
  499. if let bates = document?.bates(), let model = data.batesModel, let document = document {
  500. let pageString = self.fetchValidPageIndexString(document, model: item)
  501. KMBatesManager.defaultManager.updateCPDFBates(bates, withModel: model, Int(document.pageCount))
  502. bates.pageString = pageString
  503. bates.update()
  504. }
  505. if (FileManager.default.fileExists(atPath: path)) {
  506. try?FileManager.default.removeItem(atPath: path)
  507. }
  508. let result = document?.write(to: URL(fileURLWithPath: path)) ?? false
  509. if (result) {
  510. KMPrint("removeFile成功")
  511. self.itemSuccess(item: item)
  512. } else {
  513. KMPrint("removeFile失败")
  514. self.itemFailure(item: item, error: nil)
  515. }
  516. if i == filesData.count - 1 {
  517. self.batchSuccess()
  518. }
  519. NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: path)])
  520. }
  521. }
  522. }
  523. //MARK: 移除
  524. func removeApplay(data: KMBatchSettingItemViewModel, outputFolderPath: String) {
  525. self.removeFile(outputFolderPath: outputFolderPath, data: data as! KMBatchRemoveViewModel, filesData: self.batchFilesData)
  526. }
  527. func removeFile(outputFolderPath: String, data: KMBatchRemoveViewModel, filesData: [KMBatchProcessingTableViewModel]) {
  528. if filesData.count != 0 {
  529. for i in 0..<filesData.count {
  530. let item = filesData[i]
  531. // DispatchQueue.global().async {
  532. var path = self.fetchFilePath(type: .batchRemove, filePath: item.filePath, outputFolderPath: outputFolderPath)
  533. let document = CPDFDocument.init(url: URL(fileURLWithPath: item.filePath))
  534. if document != nil {
  535. if (document!.allowsPrinting == false || document!.allowsCopying == false) {
  536. let alert = NSAlert()
  537. alert.alertStyle = .critical
  538. alert.messageText = "此文档不允许修改"
  539. alert.runModal()
  540. return
  541. }
  542. if (data.options.contains(.security)) {
  543. }
  544. if (data.options.contains(.batesNumber)) {
  545. let property = document!.bates()
  546. property?.clear()
  547. }
  548. if (data.options.contains(.headerAndFooter)) {
  549. let property = document!.headerFooter()
  550. property?.clear()
  551. }
  552. if (data.options.contains(.background)) {
  553. let property = document!.background()
  554. property?.clear()
  555. }
  556. if (data.options.contains(.watermark)) {
  557. let array: Array<CPDFWatermark> = document!.watermarks() ?? []
  558. for model in array {
  559. document!.removeWatermark(model)
  560. }
  561. }
  562. if (FileManager.default.fileExists(atPath: path)) {
  563. try?FileManager.default.removeItem(atPath: path)
  564. }
  565. let result = document!.write(to: URL(fileURLWithPath: path))
  566. if (result) {
  567. KMPrint("removeFile成功")
  568. self.itemSuccess(item: item)
  569. } else {
  570. KMPrint("removeFile失败")
  571. self.itemFailure(item: item, error: nil)
  572. }
  573. if i == filesData.count - 1 {
  574. self.batchSuccess()
  575. }
  576. NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: outputFolderPath)])
  577. }
  578. // }
  579. }
  580. }
  581. }
  582. //MARK: 图片转PDF
  583. func imageToPDFExport(data: KMBatchSettingItemViewModel, outputFolderPath: String) {
  584. self.imageToPDFFile(outputFolderPath: outputFolderPath, data: data as! KMBatchImageToPDFModel, filesData: self.batchFilesData)
  585. }
  586. func imageToPDFFile(outputFolderPath: String, data: KMBatchImageToPDFModel, filesData: [KMBatchProcessingTableViewModel]) {
  587. if filesData.count != 0 {
  588. self.batchProgress()
  589. if data.isNewPDF {
  590. if data.isMergeAll {
  591. let item = filesData[0]
  592. let path = self.fetchFilePath(type: .imageToPDF, filePath: item.filePath, outputFolderPath: outputFolderPath)
  593. let pdfDocument = CPDFDocument()
  594. for item in filesData {
  595. pdfDocument?.km_insert(image: item.image, at: pdfDocument?.pageCount ?? 0)
  596. }
  597. if data.isOCR {
  598. let model = KMOCRModel()
  599. model.showType = .page
  600. model.saveAsPDF = true
  601. model.ocrType = data.ocrType
  602. model.languageType = data.languageType
  603. model.needTxT = data.isExtractText
  604. model.pageRangeType = .all
  605. //计算需要处理的页面
  606. let pages:[Int] = KMOCRManager.fetchPageIndex(document: pdfDocument!, model: model)
  607. model.pageRange = pages
  608. self.batchProgress()
  609. self.convertOCR(outputFolderPath: outputFolderPath, document: pdfDocument!, fileName: path.deletingPathExtension.lastPathComponent, data: model) { progress in
  610. self.batchProgress()
  611. } complete: { document, text, error in
  612. self.batchSuccess()
  613. }
  614. } else {
  615. let success = pdfDocument?.write(toFile: path)
  616. if success != nil {
  617. for item in filesData {
  618. self.itemSuccess(item: item)
  619. }
  620. self.batchSuccess()
  621. } else {
  622. self.batchFailure()
  623. }
  624. }
  625. } else {
  626. processFile(at: 0, outputFolderPath: outputFolderPath, data: data)
  627. }
  628. } else {
  629. let selectFilePath = data.selectFilePath
  630. if selectFilePath.count == 0 {
  631. let alert = NSAlert()
  632. alert.alertStyle = .critical
  633. alert.messageText = KMLocalizedString("文件未选择")
  634. alert.runModal()
  635. return
  636. }
  637. var fileName = selectFilePath.deletingPathExtension.lastPathComponent
  638. let path = self.fetchFilePath(type: .imageToPDF, filePath: selectFilePath, outputFolderPath: outputFolderPath)
  639. var pdfDocument = CPDFDocument(url: NSURL(fileURLWithPath: selectFilePath) as URL)
  640. let count: Int = Int(pdfDocument?.pageCount ?? 0)
  641. for item in filesData {
  642. pdfDocument?.km_insert(image: item.image, at: UInt(count))
  643. }
  644. if data.isOCR {
  645. let model = KMOCRModel()
  646. model.showType = .page
  647. model.saveAsPDF = true
  648. model.ocrType = data.ocrType
  649. model.languageType = data.languageType
  650. model.needTxT = data.isExtractText
  651. model.pageRangeType = .all
  652. //计算需要处理的页面
  653. let pages:[Int] = KMOCRManager.fetchPageIndex(document: pdfDocument!, model: model)
  654. model.pageRange = pages
  655. self.convertOCR(outputFolderPath: outputFolderPath, document: pdfDocument!, fileName: fileName, data: model) { progress in
  656. } complete: { document, text, error in
  657. if (error != nil) {
  658. self.batchFailure()
  659. } else {
  660. for item in filesData {
  661. self.itemSuccess(item: item)
  662. }
  663. self.batchSuccess()
  664. }
  665. }
  666. } else {
  667. let success = pdfDocument?.write(toFile: path)
  668. if success != nil {
  669. for item in filesData {
  670. self.itemSuccess(item: item)
  671. }
  672. self.batchSuccess()
  673. } else {
  674. self.batchFailure()
  675. }
  676. }
  677. }
  678. }
  679. }
  680. func processFile(at index: Int, outputFolderPath: String, data: KMBatchImageToPDFModel) {
  681. guard index < filesData.count else {
  682. self.batchSuccess()
  683. return
  684. }
  685. let item = filesData[index]
  686. if data.isOCR {
  687. let path = self.fetchFilePath(type: .imageToPDF, filePath: item.filePath, outputFolderPath: outputFolderPath)
  688. let pdfDocument = CPDFDocument()
  689. pdfDocument?.km_insert(image: item.image, at: pdfDocument?.pageCount ?? 0)
  690. let model = KMOCRModel()
  691. model.showType = .page
  692. model.saveAsPDF = true
  693. model.ocrType = data.ocrType
  694. model.languageType = data.languageType
  695. model.needTxT = data.isExtractText
  696. model.pageRangeType = .all
  697. let pages: [Int] = KMOCRManager.fetchPageIndex(document: pdfDocument!, model: model)
  698. model.pageRange = pages
  699. self.itemProgress(item: item, processValue: 0)
  700. self.convertOCR(outputFolderPath: outputFolderPath, document: pdfDocument!, fileName: path.deletingPathExtension.lastPathComponent, data: model) { [unowned self] progress in
  701. self.itemProgress(item: item, processValue: progress)
  702. } complete: { [unowned self] document, text, error in
  703. self.itemSuccess(item: filesData[index])
  704. processFile(at: index + 1, outputFolderPath: outputFolderPath, data: data)
  705. }
  706. } else {
  707. let path = self.fetchFilePath(type: .imageToPDF, filePath: item.filePath, outputFolderPath: outputFolderPath)
  708. let pdfDocument = CPDFDocument()
  709. pdfDocument?.km_insert(image: item.image, at: pdfDocument?.pageCount ?? 0)
  710. let success = pdfDocument?.write(toFile: path)
  711. if success != nil {
  712. self.itemSuccess(item: item)
  713. processFile(at: index + 1, outputFolderPath: outputFolderPath, data: data)
  714. } else {
  715. self.itemFailure(item: item, error: nil)
  716. }
  717. }
  718. }
  719. }
  720. //MARK: private
  721. extension KMBatchManager {
  722. func fetchValidPageIndexString(_ document: CPDFDocument, model: KMBatchProcessingTableViewModel) -> String? {
  723. if model.pageRange == .all {
  724. let pages = Array(0..<Int(document.pageCount))
  725. let pageIndexString = pages.isEmpty ? "" : pages.map { "\($0)" }.joined(separator: ",")
  726. return pageIndexString
  727. } else {
  728. let data = KMOCRModel()
  729. data.pageRangeType = model.pageRange
  730. data.pageRangeString = model.pageRangeString
  731. let pages:[Int] = KMOCRManager.fetchPageIndex(document: document, model: data)
  732. let pageIndexString = pages.isEmpty ? "" : pages.map { "\($0)" }.joined(separator: ",")
  733. return pageIndexString
  734. }
  735. return nil
  736. }
  737. func fetchDocument(filePath: String, model: KMBatchProcessingTableViewModel) -> CPDFDocument {
  738. var document = CPDFDocument(url: URL(fileURLWithPath: filePath))
  739. if model.password.count != 0 {
  740. document?.unlock(withPassword: model.password)
  741. }
  742. if model.pageRange == .all {
  743. } else {
  744. let data = KMOCRModel()
  745. data.pageRangeType = model.pageRange
  746. data.pageRangeString = model.pageRangeString
  747. let pages:[Int] = KMOCRManager.fetchPageIndex(document: document!, model: data)
  748. var tempDocument = CPDFDocument()
  749. for i in 0..<pages.count {
  750. let page = document?.page(at: UInt(i))
  751. tempDocument?.insertPageObject(page, at: tempDocument?.pageCount ?? 0)
  752. }
  753. let fileName = filePath.deletingPathExtension.lastPathComponent
  754. let isSuccess = tempDocument?.write(toFile: self.fetchTempFilePath(fileName: fileName))
  755. if isSuccess != nil {
  756. document = tempDocument
  757. }
  758. }
  759. return document ?? CPDFDocument()
  760. }
  761. func fetchTempFilePath(fileName: String) -> String {
  762. let floderPath = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.applicationSupportDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).last?.stringByAppendingPathComponent(Bundle.main.bundleIdentifier!).stringByAppendingPathComponent("BatchTemp")
  763. let filePath = floderPath?.stringByAppendingPathComponent("\(fileName).pdf")
  764. if let data = floderPath, !FileManager.default.fileExists(atPath: data) {
  765. try?FileManager.default.createDirectory(atPath: data, withIntermediateDirectories: false)
  766. }
  767. if let data = filePath, !FileManager.default.fileExists(atPath: data) {
  768. FileManager.default.createFile(atPath: data, contents: nil)
  769. }
  770. return filePath ?? ""
  771. }
  772. func removeTempFilePath(filePath: String) {
  773. let fileName = filePath.deletingPathExtension.lastPathComponent
  774. let path = self.fetchTempFilePath(fileName: fileName)
  775. if (FileManager.default.fileExists(atPath: path)) {
  776. try?FileManager.default.removeItem(atPath: path)
  777. }
  778. }
  779. func fetchFilePath(type: KMBatchCollectionViewType, filePath: String, outputFolderPath: String) -> String {
  780. var fileName = filePath.deletingPathExtension.lastPathComponent
  781. if fileName.isEmpty {
  782. fileName = NSLocalizedString("Untitled", comment: "")
  783. }
  784. var path = outputFolderPath + "/" + fileName + ".pdf"
  785. // // 检查文件是否已存在,如果存在,则添加数字后缀
  786. // var finalPath = path
  787. // var count = 1
  788. // while FileManager.default.fileExists(atPath: finalPath) {
  789. // let newFileName = "\(fileName) \(count)"
  790. // finalPath = outputFolderPath + "/" + newFileName + ".pdf"
  791. // count += 1
  792. // }
  793. // 使用最终路径进行保存或其他操作
  794. // path = finalPath
  795. return path
  796. }
  797. }
  798. //MARK: Alert
  799. extension KMBatchManager {
  800. func batchUnkown() {
  801. self.state = .unknow
  802. NotificationCenter.default.post(name: NSNotification.Name(kBacthProcessNotification), object: nil)
  803. }
  804. func batchProgress() {
  805. for item in filesData {
  806. self.itemProgress(item: item, processValue: 0)
  807. }
  808. self.state = .processing
  809. NotificationCenter.default.post(name: NSNotification.Name(kBacthProcessNotification), object: nil)
  810. }
  811. func batchSuccess() {
  812. self.state = .complete
  813. NotificationCenter.default.post(name: NSNotification.Name(kBacthProcessNotification), object: nil)
  814. }
  815. func batchFailure() {
  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. }