KMBatchManager.swift 53 KB

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