KMBatchManager.swift 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632
  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. break
  58. case .background:
  59. break
  60. case .headerAndFooter:
  61. break
  62. case .batesNumber:
  63. break
  64. case .batchRemove:
  65. self.removeApplay(data: data, outputFolderPath: outputFolderPath)
  66. break
  67. default:
  68. KMPrint("找不到")
  69. break
  70. }
  71. //
  72. self.batchProgress()
  73. }
  74. }
  75. }
  76. protocol KMBatchSettingViewExport {}
  77. extension KMBatchManager: KMBatchSettingViewExport {
  78. //MARK: 转档
  79. func convertPDFExport(data: KMBatchSettingItemViewModel, outputFolderPath: String) {
  80. self.convertFile(outputFolderPath: outputFolderPath, data: data, filesData: self.batchFilesData)
  81. }
  82. func convertFile(outputFolderPath: String, data: KMBatchSettingItemViewModel, filesData: [KMBatchProcessingTableViewModel]) {
  83. if filesData.count != 0 {
  84. DispatchQueue.global().async {
  85. for i in 0..<filesData.count {
  86. let item = filesData[i]
  87. //创建Document
  88. let filePath = item.filePath
  89. let document = self.fetchDocument(filePath: filePath, model: item)
  90. let settingData = data as? KMBatchConvertPDFViewModel ?? KMBatchConvertPDFViewModel()
  91. var fileName = filePath.deletingPathExtension.lastPathComponent
  92. if ((fileName.isEmpty)) {
  93. fileName = NSLocalizedString("Untitled", comment: "")
  94. }
  95. let convert = self.addConvertParameter(settingData)
  96. let pageCount = document.pageCount
  97. //获取page
  98. var pages:[Int] = []
  99. for i in 0..<pageCount {
  100. pages.append(Int(i)+1)
  101. }
  102. convert.outputFolderPath = outputFolderPath
  103. convert.filePath = filePath
  104. convert.outputFileName = fileName
  105. convert.pages = pages
  106. convert.isAllowOCR = settingData.needRecognizeText
  107. convert.ocrLanguage = settingData.languageType
  108. item.state = .clock
  109. KMPDFConvertManager.defaultManager.convert(convert: convert, progress: { [unowned self] progressValue in
  110. print("转档进度 - \(progressValue)")
  111. let progress = Float(progressValue) / Float(pageCount)
  112. self.itemProgress(item: item, processValue: progress)
  113. }, completion: { [unowned self] finished, error in
  114. if finished {
  115. if FileManager.default.fileExists(atPath: outputFolderPath) {
  116. NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: outputFolderPath)])
  117. }
  118. self.itemSuccess(item: item)
  119. } else {
  120. self.itemFailure(item: item, error: error! as NSError)
  121. }
  122. if i == filesData.count - 1 {
  123. self.batchSuccess()
  124. }
  125. })
  126. }
  127. }
  128. }
  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:
  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 (convert.convertType == .jpeg) {
  202. (convert as! KMPDFConvertImage).imageType = .JPEG
  203. (convert as! KMPDFConvertImage).imageDpi = dpi
  204. } else if (convert.convertType == .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 fileName = item.filePath.deletingPathExtension.lastPathComponent
  240. if ((fileName.isEmpty)) {
  241. fileName = NSLocalizedString("Untitled", comment: "")
  242. }
  243. let path = outputFolderPath + "/" + fileName + ".pdf"
  244. KMOCRManager.manager.convertBatchOCR(document: document!, saveFilePath: path, model: data, progress: { [unowned self] progress in
  245. self.itemProgress(item: item, processValue: progress)
  246. }) { [unowned self] document, text, error in
  247. if error == nil {
  248. self.itemSuccess(item: item)
  249. } else {
  250. self.itemFailure(item: item, error: error! as NSError)
  251. }
  252. if i == filesData.count - 1 {
  253. self.batchSuccess()
  254. }
  255. }
  256. }
  257. }
  258. }
  259. //MARK: 压缩
  260. func compressExport(data: KMBatchSettingItemViewModel, outputFolderPath: String) {
  261. self.compressFile(outputFolderPath: outputFolderPath, data: (data as? KMCompressSettingModel)!, filesData: self.batchFilesData)
  262. }
  263. func compressFile(outputFolderPath: String, data: KMCompressSettingModel, filesData: [KMBatchProcessingTableViewModel]) {
  264. if filesData.count != 0 {
  265. for i in 0..<filesData.count {
  266. let item = filesData[i]
  267. let document = CPDFDocument.init(url: URL(fileURLWithPath: item.filePath))
  268. if document != nil {
  269. var fileName = item.filePath.deletingPathExtension.lastPathComponent
  270. if ((fileName.isEmpty)) {
  271. fileName = NSLocalizedString("Untitled", comment: "")
  272. }
  273. let path = outputFolderPath + "/" + fileName + ".pdf"
  274. KMCompressManager.shared.compress(documentURL: URL(fileURLWithPath: item.filePath), fileURL: URL(fileURLWithPath: path), limit: false, model: data) { currentPage, totalPages in
  275. let progress = Float(currentPage) / Float(totalPages)
  276. self.itemProgress(item: item, processValue: progress)
  277. } cancelHandler: {
  278. return false
  279. } completionHandler: { [unowned self] isFinish in
  280. if isFinish {
  281. self.itemSuccess(item: item)
  282. } else {
  283. self.itemFailure(item: item, error: nil)
  284. }
  285. if i == filesData.count - 1 {
  286. self.batchSuccess()
  287. }
  288. }
  289. }
  290. }
  291. }
  292. }
  293. //MARK: 安全
  294. func securityExport(data: KMBatchSettingItemViewModel, outputFolderPath: String) {
  295. self.securityFile(outputFolderPath: outputFolderPath, data: data as! KMBatchSecurityViewModel, filesData: self.batchFilesData)
  296. }
  297. func securityFile(outputFolderPath: String, data: KMBatchSecurityViewModel, filesData: [KMBatchProcessingTableViewModel]) {
  298. if filesData.count != 0 {
  299. for i in 0..<filesData.count {
  300. let item = filesData[i]
  301. let docuemt = CPDFDocument.init(url: URL(fileURLWithPath: item.filePath))
  302. if (docuemt != nil) {
  303. var fileName = item.filePath.deletingPathExtension.lastPathComponent
  304. if ((fileName.isEmpty)) {
  305. fileName = NSLocalizedString("Untitled", comment: "")
  306. }
  307. let path = outputFolderPath + "/" + fileName + ".pdf"
  308. var options: [CPDFDocumentWriteOption : Any] = [:]
  309. //开启密码
  310. if data.isOpenPassword &&
  311. !data.openPasswordString.isEmpty {
  312. options.updateValue(data.openPasswordString, forKey: .userPasswordOption)
  313. }
  314. //
  315. //权限密码
  316. if data.isPermission &&
  317. !data.permissionString.isEmpty {
  318. options.updateValue(data.permissionString, forKey: .ownerPasswordOption)
  319. }
  320. // 限制打印
  321. if data.restrictOptions.contains(.print) {
  322. options.updateValue(false, forKey: .allowsPrintingOption)
  323. } else {
  324. options.updateValue(true, forKey: .allowsPrintingOption)
  325. }
  326. //限制复制
  327. if data.restrictOptions.contains(.copy) {
  328. options.updateValue(false, forKey: .allowsCopyingOption)
  329. } else {
  330. options.updateValue(true, forKey: .allowsCopyingOption)
  331. }
  332. let result = docuemt!.write(toFile: path, withOptions: options)
  333. // let result = docuemt!.write(to: URL(fileURLWithPath: path), withOptions: options)
  334. if result {
  335. KMPrint("成功")
  336. self.itemSuccess(item: item)
  337. } else {
  338. KMPrint("失败")
  339. self.itemFailure(item: item, error: nil)
  340. }
  341. if i == filesData.count - 1 {
  342. self.batchSuccess()
  343. NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: outputFolderPath)])
  344. }
  345. }
  346. }
  347. }
  348. }
  349. func waterMarkApplay(data: KMBatchSettingItemViewModel) {
  350. }
  351. // func waterMarkFile(data: KMWatermarkAdjectiveBaseModel, filesData: [KMBatchProcessingTableViewModel]?) {
  352. //
  353. // }
  354. func backgroundApplay(data: KMBatchSettingItemViewModel) {
  355. }
  356. func backgroundFile(outputFolderPath: String, data: KMBackgroundModel, filesData: [KMBatchProcessingTableViewModel]?) {
  357. }
  358. func headAndFooterApplay(data: KMBatchSettingItemViewModel) {
  359. }
  360. // func headAndFooterFile(outputFolderPath: String, data: KMHeaderFooterModel, filesData: [KMBatchProcessingTableViewModel]?) {
  361. //
  362. // }
  363. func batesApplay(data: KMBatchSettingItemViewModel) {
  364. }
  365. func batesFile(outputFolderPath: String, data: KMBatesModel, filesData: [KMBatchProcessingTableViewModel]?) {
  366. }
  367. func removeApplay(data: KMBatchSettingItemViewModel, outputFolderPath: String) {
  368. self.removeFile(outputFolderPath: outputFolderPath, data: data as! KMBatchRemoveViewModel, filesData: self.batchFilesData)
  369. }
  370. func removeFile(outputFolderPath: String, data: KMBatchRemoveViewModel, filesData: [KMBatchProcessingTableViewModel]) {
  371. if filesData.count != 0 {
  372. for i in 0..<filesData.count {
  373. let item = filesData[i]
  374. // DispatchQueue.global().async {
  375. var fileName = item.filePath.deletingPathExtension.lastPathComponent
  376. if ((fileName.isEmpty)) {
  377. fileName = NSLocalizedString("Untitled", comment: "")
  378. }
  379. let path = outputFolderPath + "/" + fileName + ".pdf"
  380. let document = CPDFDocument.init(url: URL(fileURLWithPath: item.filePath))
  381. if document != nil {
  382. if (document!.allowsPrinting == false || document!.allowsCopying == false) {
  383. let alert = NSAlert()
  384. alert.alertStyle = .critical
  385. alert.messageText = "此文档不允许修改"
  386. alert.runModal()
  387. return
  388. }
  389. if (data.options.contains(.security)) {
  390. }
  391. if (data.options.contains(.batesNumber)) {
  392. let property = document!.bates()
  393. property?.clear()
  394. }
  395. if (data.options.contains(.headerAndFooter)) {
  396. let property = document!.headerFooter()
  397. property?.clear()
  398. }
  399. if (data.options.contains(.background)) {
  400. let property = document!.background()
  401. property?.clear()
  402. }
  403. if (data.options.contains(.watermark)) {
  404. let array: Array<CPDFWatermark> = document!.watermarks() ?? []
  405. for model in array {
  406. document!.removeWatermark(model)
  407. }
  408. }
  409. if (FileManager.default.fileExists(atPath: path)) {
  410. try?FileManager.default.removeItem(atPath: path)
  411. }
  412. let result = document!.write(to: URL(fileURLWithPath: path))
  413. if (result) {
  414. KMPrint("removeFile成功")
  415. self.itemSuccess(item: item)
  416. } else {
  417. KMPrint("removeFile失败")
  418. self.itemFailure(item: item, error: nil)
  419. }
  420. if i == filesData.count - 1 {
  421. self.batchSuccess()
  422. }
  423. NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: outputFolderPath)])
  424. }
  425. // }
  426. }
  427. }
  428. }
  429. }
  430. //MARK: private
  431. extension KMBatchManager {
  432. func fetchDocument(filePath: String, model: KMBatchProcessingTableViewModel) -> CPDFDocument {
  433. var document = CPDFDocument(url: URL(fileURLWithPath: filePath))
  434. if model.pageRange == .all {
  435. } else {
  436. let data = KMOCRModel()
  437. data.pageRangeType = model.pageRange
  438. data.pageRangeString = model.pageRangeString
  439. let pages:[Int] = KMOCRManager.manager.fetchPageIndex(document: document!, model: data)
  440. var tempDocument = CPDFDocument()
  441. for i in 0..<pages.count {
  442. let page = document?.page(at: UInt(i))
  443. tempDocument?.insertPageObject(page, at: tempDocument?.pageCount ?? 0)
  444. }
  445. let fileName = filePath.deletingPathExtension.lastPathComponent
  446. let isSuccess = tempDocument?.write(toFile: self.fetchTempFilePath(fileName: fileName))
  447. if isSuccess != nil {
  448. document = tempDocument
  449. }
  450. }
  451. return document ?? CPDFDocument()
  452. }
  453. func fetchTempFilePath(fileName: String) -> String {
  454. let floderPath = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.applicationSupportDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).last?.stringByAppendingPathComponent(Bundle.main.bundleIdentifier!).stringByAppendingPathComponent("BatchTemp")
  455. let filePath = floderPath?.stringByAppendingPathComponent("\(fileName).pdf")
  456. if let data = floderPath, !FileManager.default.fileExists(atPath: data) {
  457. try?FileManager.default.createDirectory(atPath: data, withIntermediateDirectories: false)
  458. }
  459. if let data = filePath, !FileManager.default.fileExists(atPath: data) {
  460. FileManager.default.createFile(atPath: data, contents: nil)
  461. }
  462. return filePath ?? ""
  463. }
  464. func removeTempFilePath(filePath: String) {
  465. let fileName = filePath.deletingPathExtension.lastPathComponent
  466. let path = self.fetchTempFilePath(fileName: fileName)
  467. if (FileManager.default.fileExists(atPath: path)) {
  468. try?FileManager.default.removeItem(atPath: path)
  469. }
  470. }
  471. }
  472. //MARK: Alert
  473. extension KMBatchManager {
  474. func batchUnkown() {
  475. self.state = .unknow
  476. NotificationCenter.default.post(name: NSNotification.Name(kBacthProcessNotification), object: nil)
  477. }
  478. func batchProgress() {
  479. self.state = .processing
  480. NotificationCenter.default.post(name: NSNotification.Name(kBacthProcessNotification), object: nil)
  481. }
  482. func batchSuccess() {
  483. self.state = .complete
  484. NotificationCenter.default.post(name: NSNotification.Name(kBacthProcessNotification), object: nil)
  485. }
  486. func batchFailure() {
  487. self.state = .error
  488. NotificationCenter.default.post(name: NSNotification.Name(kBacthProcessNotification), object: nil)
  489. }
  490. func itemProgress(item: KMBatchProcessingTableViewModel, processValue: Float) {
  491. if processValue > 0.7 {
  492. item.state = .loading70
  493. } else {
  494. item.state = .loading
  495. }
  496. NotificationCenter.default.post(name: NSNotification.Name(kBacthFilesProcessNotification), object: item)
  497. }
  498. func itemSuccess(item: KMBatchProcessingTableViewModel) {
  499. self.removeTempFilePath(filePath: item.filePath)
  500. item.state = .success
  501. NotificationCenter.default.post(name: NSNotification.Name(kBacthFilesProcessNotification), object: item)
  502. }
  503. func itemFailure(item: KMBatchProcessingTableViewModel, error: NSError?) {
  504. self.removeTempFilePath(filePath: item.filePath)
  505. item.state = .error
  506. NotificationCenter.default.post(name: NSNotification.Name(kBacthFilesProcessNotification), object: item)
  507. guard let error = error else { return }
  508. var errorString = ""
  509. let myError: NSError = error as NSError
  510. if myError.code == 1 {
  511. errorString = NSLocalizedString("Password required or incorrect password. Please re-enter your password and try again", comment: "")
  512. } else if myError.code == 2 {
  513. errorString = NSLocalizedString("The license doesn't allow the permission", comment: "")
  514. } else if myError.code == 3 {
  515. errorString = NSLocalizedString("Malloc failure", comment: "")
  516. } else if myError.code == 4 {
  517. errorString = NSLocalizedString("Unknown error in processing conversion. Please try again later", comment: "")
  518. } else if myError.code == 5 {
  519. errorString = NSLocalizedString("Unknown error in processing PDF. Please try again later", comment: "")
  520. } else if myError.code == 6 {
  521. errorString = NSLocalizedString("File not found or could not be opened. Check if your file exists or choose another file to convert", comment: "")
  522. } else if myError.code == 7 {
  523. errorString = NSLocalizedString("File not in PDF format or corruptead. Change a PDF file and try again", comment: "")
  524. } else if myError.code == 8 {
  525. errorString = NSLocalizedString("Unsupported security scheme", comment: "")
  526. } else if myError.code == 9 {
  527. errorString = NSLocalizedString("Page not found or content error", comment: "")
  528. } else {
  529. errorString = NSLocalizedString("Table not found", comment: "")
  530. }
  531. let alert = NSAlert()
  532. alert.alertStyle = .critical
  533. alert.messageText = NSLocalizedString("Conversion Failed", comment: "")
  534. alert.informativeText = errorString
  535. alert.addButton(withTitle: NSLocalizedString("OK", comment: ""))
  536. alert.runModal()
  537. }
  538. }