KMBatchManager.swift 43 KB

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