KMBatchManager.swift 44 KB

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