KMBatchManager.swift 44 KB

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