KMBatchManager.swift 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994
  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. var fileName = data.selectFilePath.deletingPathExtension.lastPathComponent
  632. let path = self.fetchFilePath(type: .imageToPDF, filePath: data.selectFilePath, outputFolderPath: outputFolderPath)
  633. var pdfDocument = CPDFDocument(url: NSURL(fileURLWithPath: data.selectFilePath) as URL)
  634. let count: Int = Int(pdfDocument?.pageCount ?? 0)
  635. for item in filesData {
  636. pdfDocument?.km_insert(image: item.image, at: pdfDocument?.pageCount ?? 0)
  637. }
  638. if data.isOCR {
  639. let model = KMOCRModel()
  640. model.showType = .page
  641. model.saveAsPDF = true
  642. model.ocrType = data.ocrType
  643. model.languageType = data.languageType
  644. model.needTxT = data.isExtractText
  645. model.pageRangeType = .all
  646. //计算需要处理的页面
  647. let pages:[Int] = KMOCRManager.fetchPageIndex(document: pdfDocument!, model: model)
  648. model.pageRange = pages
  649. self.convertOCR(outputFolderPath: outputFolderPath, document: pdfDocument!, fileName: fileName, data: model) { progress in
  650. } complete: { document, text, error in
  651. if (error != nil) {
  652. self.batchFailure()
  653. } else {
  654. for item in filesData {
  655. self.itemSuccess(item: item)
  656. }
  657. self.batchSuccess()
  658. }
  659. }
  660. } else {
  661. let success = pdfDocument?.write(toFile: path)
  662. if success != nil {
  663. for item in filesData {
  664. self.itemSuccess(item: item)
  665. }
  666. self.batchSuccess()
  667. } else {
  668. self.batchFailure()
  669. }
  670. }
  671. }
  672. }
  673. }
  674. func processFile(at index: Int, outputFolderPath: String, data: KMBatchImageToPDFModel) {
  675. guard index < filesData.count else {
  676. self.batchSuccess()
  677. return
  678. }
  679. let item = filesData[index]
  680. if data.isOCR {
  681. let path = self.fetchFilePath(type: .imageToPDF, filePath: item.filePath, outputFolderPath: outputFolderPath)
  682. let pdfDocument = CPDFDocument()
  683. pdfDocument?.km_insert(image: item.image, at: pdfDocument?.pageCount ?? 0)
  684. let model = KMOCRModel()
  685. model.showType = .page
  686. model.saveAsPDF = true
  687. model.ocrType = data.ocrType
  688. model.languageType = data.languageType
  689. model.needTxT = data.isExtractText
  690. model.pageRangeType = .all
  691. let pages: [Int] = KMOCRManager.fetchPageIndex(document: pdfDocument!, model: model)
  692. model.pageRange = pages
  693. self.itemProgress(item: item, processValue: 0)
  694. self.convertOCR(outputFolderPath: outputFolderPath, document: pdfDocument!, fileName: path.deletingPathExtension.lastPathComponent, data: model) { [unowned self] progress in
  695. self.itemProgress(item: item, processValue: progress)
  696. } complete: { [unowned self] document, text, error in
  697. self.itemSuccess(item: filesData[index])
  698. processFile(at: index + 1, outputFolderPath: outputFolderPath, data: data)
  699. }
  700. } else {
  701. let path = self.fetchFilePath(type: .imageToPDF, filePath: item.filePath, outputFolderPath: outputFolderPath)
  702. let pdfDocument = CPDFDocument()
  703. pdfDocument?.km_insert(image: item.image, at: pdfDocument?.pageCount ?? 0)
  704. let success = pdfDocument?.write(toFile: path)
  705. if success != nil {
  706. self.itemSuccess(item: item)
  707. processFile(at: index + 1, outputFolderPath: outputFolderPath, data: data)
  708. } else {
  709. self.itemFailure(item: item, error: nil)
  710. }
  711. }
  712. }
  713. }
  714. //MARK: private
  715. extension KMBatchManager {
  716. func fetchValidPageIndexString(_ document: CPDFDocument, model: KMBatchProcessingTableViewModel) -> String? {
  717. if model.pageRange == .all {
  718. let pages = Array(0..<Int(document.pageCount))
  719. let pageIndexString = pages.isEmpty ? "" : pages.map { "\($0)" }.joined(separator: ",")
  720. return pageIndexString
  721. } else {
  722. let data = KMOCRModel()
  723. data.pageRangeType = model.pageRange
  724. data.pageRangeString = model.pageRangeString
  725. let pages:[Int] = KMOCRManager.fetchPageIndex(document: document, model: data)
  726. let pageIndexString = pages.isEmpty ? "" : pages.map { "\($0)" }.joined(separator: ",")
  727. return pageIndexString
  728. }
  729. return nil
  730. }
  731. func fetchDocument(filePath: String, model: KMBatchProcessingTableViewModel) -> CPDFDocument {
  732. var document = CPDFDocument(url: URL(fileURLWithPath: filePath))
  733. if model.password.count != 0 {
  734. document?.unlock(withPassword: model.password)
  735. }
  736. if model.pageRange == .all {
  737. } else {
  738. let data = KMOCRModel()
  739. data.pageRangeType = model.pageRange
  740. data.pageRangeString = model.pageRangeString
  741. let pages:[Int] = KMOCRManager.fetchPageIndex(document: document!, model: data)
  742. var tempDocument = CPDFDocument()
  743. for i in 0..<pages.count {
  744. let page = document?.page(at: UInt(i))
  745. tempDocument?.insertPageObject(page, at: tempDocument?.pageCount ?? 0)
  746. }
  747. let fileName = filePath.deletingPathExtension.lastPathComponent
  748. let isSuccess = tempDocument?.write(toFile: self.fetchTempFilePath(fileName: fileName))
  749. if isSuccess != nil {
  750. document = tempDocument
  751. }
  752. }
  753. return document ?? CPDFDocument()
  754. }
  755. func fetchTempFilePath(fileName: String) -> String {
  756. let floderPath = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.applicationSupportDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).last?.stringByAppendingPathComponent(Bundle.main.bundleIdentifier!).stringByAppendingPathComponent("BatchTemp")
  757. let filePath = floderPath?.stringByAppendingPathComponent("\(fileName).pdf")
  758. if let data = floderPath, !FileManager.default.fileExists(atPath: data) {
  759. try?FileManager.default.createDirectory(atPath: data, withIntermediateDirectories: false)
  760. }
  761. if let data = filePath, !FileManager.default.fileExists(atPath: data) {
  762. FileManager.default.createFile(atPath: data, contents: nil)
  763. }
  764. return filePath ?? ""
  765. }
  766. func removeTempFilePath(filePath: String) {
  767. let fileName = filePath.deletingPathExtension.lastPathComponent
  768. let path = self.fetchTempFilePath(fileName: fileName)
  769. if (FileManager.default.fileExists(atPath: path)) {
  770. try?FileManager.default.removeItem(atPath: path)
  771. }
  772. }
  773. func fetchFilePath(type: KMBatchCollectionViewType, filePath: String, outputFolderPath: String) -> String {
  774. var fileName = filePath.deletingPathExtension.lastPathComponent
  775. if fileName.isEmpty {
  776. fileName = NSLocalizedString("Untitled", comment: "")
  777. }
  778. var path = outputFolderPath + "/" + fileName + ".pdf"
  779. // // 检查文件是否已存在,如果存在,则添加数字后缀
  780. // var finalPath = path
  781. // var count = 1
  782. // while FileManager.default.fileExists(atPath: finalPath) {
  783. // let newFileName = "\(fileName) \(count)"
  784. // finalPath = outputFolderPath + "/" + newFileName + ".pdf"
  785. // count += 1
  786. // }
  787. // 使用最终路径进行保存或其他操作
  788. // path = finalPath
  789. return path
  790. }
  791. }
  792. //MARK: Alert
  793. extension KMBatchManager {
  794. func batchUnkown() {
  795. self.state = .unknow
  796. NotificationCenter.default.post(name: NSNotification.Name(kBacthProcessNotification), object: nil)
  797. }
  798. func batchProgress() {
  799. for item in filesData {
  800. self.itemProgress(item: item, processValue: 0)
  801. }
  802. self.state = .processing
  803. NotificationCenter.default.post(name: NSNotification.Name(kBacthProcessNotification), object: nil)
  804. }
  805. func batchSuccess() {
  806. self.state = .complete
  807. NotificationCenter.default.post(name: NSNotification.Name(kBacthProcessNotification), object: nil)
  808. }
  809. func batchFailure() {
  810. self.state = .error
  811. NotificationCenter.default.post(name: NSNotification.Name(kBacthProcessNotification), object: nil)
  812. }
  813. func itemProgress(item: KMBatchProcessingTableViewModel, processValue: Float) {
  814. if processValue > 0.7 {
  815. item.state = .loading70
  816. } else {
  817. item.state = .loading
  818. }
  819. NotificationCenter.default.post(name: NSNotification.Name(kBacthFilesProcessNotification), object: item)
  820. }
  821. func itemSuccess(item: KMBatchProcessingTableViewModel) {
  822. self.removeTempFilePath(filePath: item.filePath)
  823. item.state = .success
  824. NotificationCenter.default.post(name: NSNotification.Name(kBacthFilesProcessNotification), object: item)
  825. }
  826. func itemFailure(item: KMBatchProcessingTableViewModel, error: NSError?) {
  827. self.removeTempFilePath(filePath: item.filePath)
  828. item.state = .error
  829. NotificationCenter.default.post(name: NSNotification.Name(kBacthFilesProcessNotification), object: item)
  830. guard let error = error else { return }
  831. var errorString = ""
  832. let myError: NSError = error as NSError
  833. if myError.code == 1 {
  834. errorString = NSLocalizedString("Password required or incorrect password. Please re-enter your password and try again", comment: "")
  835. } else if myError.code == 2 {
  836. errorString = NSLocalizedString("The license doesn't allow the permission", comment: "")
  837. } else if myError.code == 3 {
  838. errorString = NSLocalizedString("Malloc failure", comment: "")
  839. } else if myError.code == 4 {
  840. errorString = NSLocalizedString("Unknown error in processing conversion. Please try again later", comment: "")
  841. } else if myError.code == 5 {
  842. errorString = NSLocalizedString("Unknown error in processing PDF. Please try again later", comment: "")
  843. } else if myError.code == 6 {
  844. errorString = NSLocalizedString("File not found or could not be opened. Check if your file exists or choose another file to convert", comment: "")
  845. } else if myError.code == 7 {
  846. errorString = NSLocalizedString("File not in PDF format or corruptead. Change a PDF file and try again", comment: "")
  847. } else if myError.code == 8 {
  848. errorString = NSLocalizedString("Unsupported security scheme", comment: "")
  849. } else if myError.code == 9 {
  850. errorString = NSLocalizedString("Page not found or content error", comment: "")
  851. } else {
  852. errorString = NSLocalizedString("Table not found", comment: "")
  853. }
  854. let alert = NSAlert()
  855. alert.alertStyle = .critical
  856. alert.messageText = NSLocalizedString("Conversion Failed", comment: "")
  857. alert.informativeText = errorString
  858. alert.addButton(withTitle: NSLocalizedString("OK", comment: ""))
  859. alert.runModal()
  860. }
  861. }