1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021 |
- //
- // KMBatchManager.swift
- // PDF Master
- //
- // Created by lizhe on 2023/2/17.
- //
- import Cocoa
- enum KMBatchManagerSate: Int, CaseIterable {
- case unknow = 0
- case processing
- case complete
- case error
- }
- let kBacthFilesProcessNotification = "kBacthFilesProcessNotification"
- let kBacthProcessNotification = "kBacthProcessNotification"
- class KMBatchManager: NSObject {
- public static let manager = KMBatchManager()
- fileprivate(set) var state: KMBatchManagerSate = .unknow
-
- var outputFolderPath: String = ""
-
- var filesData: [KMBatchProcessingTableViewModel] = []
- var batchFilesData: [KMBatchProcessingTableViewModel] {
- get {
- var resultArray:[KMBatchProcessingTableViewModel] = []
- for item in filesData {
- if !item.isLock {
- resultArray.append(item)
- }
- }
- return resultArray
- }
- }
-
- func batch(type: KMBatchCollectionViewType, data: KMBatchSettingItemViewModel) {
- let panel = NSOpenPanel()
- panel.canChooseFiles = false
- panel.canChooseDirectories = true
- panel.canCreateDirectories = true
- panel.beginSheetModal(for: NSWindow.currentWindow()) { response in
- if response == .cancel {
- return
- }
-
- let outputFolderPath = (panel.url?.path)!
- self.outputFolderPath = outputFolderPath
- //
- self.batchUnkown()
- self.batchProgress()
- switch type {
- case .convertPDF:
- self.convertPDFExport(data: data, outputFolderPath: outputFolderPath)
- break
- case .OCR:
- self.convertOCRExport(data: data, outputFolderPath: outputFolderPath)
- break
- case .compress:
- self.compressExport(data: data, outputFolderPath: outputFolderPath)
- break
- case .security:
- self.securityExport(data: data, outputFolderPath: outputFolderPath)
- break
- case .watermark:
- self.waterMarkApplay(data: data, outputFolderPath: outputFolderPath)
- break
- case .background:
- self.backgroundApplay(data: data, outputFolderPath: outputFolderPath)
- break
- case .headerAndFooter:
- self.headAndFooterApplay(data: data, outputFolderPath: outputFolderPath)
- break
- case .batesNumber:
- self.batesApplay(data: data, outputFolderPath: outputFolderPath)
- break
- case .batchRemove:
- self.removeApplay(data: data, outputFolderPath: outputFolderPath)
- break
- case .imageToPDF:
- self.imageToPDFExport(data: data, outputFolderPath: outputFolderPath)
- break
- default:
- KMPrint("找不到")
- break
- }
- }
- }
- }
- //MARK: 批量
- extension KMBatchManager {
- //MARK: 转档
- func convertPDFExport(data: KMBatchSettingItemViewModel, outputFolderPath: String) {
- self.convertFile(outputFolderPath: outputFolderPath, data: data, filesData: self.batchFilesData)
- }
-
- func convertFile(outputFolderPath: String, data: KMBatchSettingItemViewModel, filesData: [KMBatchProcessingTableViewModel]) {
- guard !filesData.isEmpty else { return }
- func processFile(at index: Int) {
- guard index < filesData.count else {
- self.batchSuccess()
- return
- }
- let item = filesData[index]
- let filePath = item.filePath
- let document = self.fetchDocument(filePath: filePath, model: item)
- let settingData = data as? KMBatchConvertPDFViewModel ?? KMBatchConvertPDFViewModel()
- let path = self.fetchFilePath(type: .convertPDF, filePath: filePath, outputFolderPath: outputFolderPath)
- let convert = self.addConvertParameter(settingData)
- let pageCount = document.pageCount
- // 获取页面
- let pages: [Int] = Array(1...Int(pageCount))
- convert.outputFolderPath = outputFolderPath
- convert.filePath = filePath
- convert.password = item.password
- convert.outputFileName = path.deletingPathExtension.lastPathComponent
- convert.pages = pages
- convert.isAllowOCR = settingData.needRecognizeText
- convert.ocrLanguage = settingData.languageType
- item.state = .clock
- KMPDFConvertManager.defaultManager.convert(convert: convert, progress: { [unowned self] progressValue in
- print("转档进度 - \(progressValue)")
- let progress = Float(progressValue) / Float(pageCount)
- self.itemProgress(item: item, processValue: progress)
- }, completion: { [unowned self] finished, error in
- if finished {
- self.itemSuccess(item: item)
- } else {
- self.itemFailure(item: item, error: error! as NSError)
- }
- processFile(at: index + 1)
- })
- }
- // 开始处理第一个文件
- processFile(at: 0)
- }
-
- func addConvertParameter(_ data: KMBatchConvertPDFViewModel) -> KMPDFConvert {
- let settingData = data
- var convert = KMPDFConvert()
-
- switch settingData.convertPDFType {
- case .word:
- convert = KMPDFConvertWord()
- if settingData.layoutSettingType == .flowingText {
- convert.isAllInOneSheet = false
- } else {
- convert.isAllInOneSheet = true
- }
- case .excel:
- convert = KMPDFConvertExcel()
- if settingData.excelSetting == .separate {
- convert.isAllInOneSheet = false
- convert.isExtractTable = false
- } else if settingData.excelSetting == .format {
- convert.isAllInOneSheet = true
- convert.isExtractTable = false
- } else if settingData.excelSetting == .tables {
- convert.isAllInOneSheet = false
- convert.isExtractTable = true
-
- switch settingData.excelTablesType {
- case .oneTable:
- convert.extractTableIndex = 0
- case .pageTable:
- convert.extractTableIndex = 1
- case .allTable:
- convert.extractTableIndex = 2
- default:
- KMPrint("未找到")
- }
- }
- case .ppt:
- convert = KMPDFConvertPPT()
- case .csv:
- convert = KMPDFConvertCSV()
- if settingData.csvOnlyTables {
- convert.isExtractTable = true
- switch settingData.excelTablesType {
- case .oneTable:
- convert.extractTableIndex = 0
- case .pageTable:
- convert.extractTableIndex = 1
- case .allTable:
- convert.extractTableIndex = 2
- default:
- KMPrint("未找到")
- }
- } else {
- convert.isExtractTable = false
- }
- case .image, .jpeg, .jpg, .jpeg2000, .bmp, .tiff, .png, .tga:
- convert = KMPDFConvertImage()
- convert.convertType = data.imageType
-
- var dpi: Int = 150
- if data.imageDpiIndex == 0 {
- dpi = 50
- } else if data.imageDpiIndex == 1 {
- dpi = 72
- } else if data.imageDpiIndex == 2 {
- dpi = 96
- } else if data.imageDpiIndex == 3 {
- dpi = 150
- } else if data.imageDpiIndex == 4 {
- dpi = 300
- } else if data.imageDpiIndex == 5 {
- dpi = 600
- } else {
- dpi = 150
- }
-
- if (data.imageType == .jpeg) {
- (convert as! KMPDFConvertImage).imageType = .JPEG
- (convert as! KMPDFConvertImage).imageDpi = dpi
-
- } else if (data.imageType == .png) {
- (convert as! KMPDFConvertImage).imageType = .PNG
- (convert as! KMPDFConvertImage).imageDpi = dpi
- } else {
- (convert as! KMPDFConvertImage).imageDpi = 150
- }
- case .html:
- convert = KMPDFConvertHTML()
- case .rtf:
- convert = KMPDFConvertRTF()
- case .json:
- convert = KMPDFConvertJson()
- if settingData.jsonType == .extractText {
- convert.isAllInOneSheet = false
- } else {
- convert.isAllInOneSheet = true
- }
- case .text:
- convert = KMPDFConvertText()
-
- default:
- KMPrint("不清楚")
- }
- return convert
- }
-
- //MARK: OCR
- func convertOCRExport(data: KMBatchSettingItemViewModel, outputFolderPath: String) {
- self.convertOCR(outputFolderPath: outputFolderPath, data: data as! KMOCRModel, filesData: self.batchFilesData)
- }
-
- func convertOCR(outputFolderPath: String, data: KMOCRModel, filesData: [KMBatchProcessingTableViewModel]?) {
- guard let filesData = filesData else { return }
- for i in 0..<filesData.count {
- let item = (filesData[i])
- let document = CPDFDocument.init(url: URL(fileURLWithPath: item.filePath))
- if document != nil {
- //计算需要处理的页面
-
- let path = self.fetchFilePath(type: .OCR, filePath: item.filePath, outputFolderPath: outputFolderPath)
- data.pageRange = self.fetchValidPageIndexs(document!, model: item) ?? []
-
- self.convertOCR(outputFolderPath: outputFolderPath, document: document!, fileName: path.deletingPathExtension.lastPathComponent, data: data) { [unowned self] progress in
- self.itemProgress(item: item, processValue: progress)
- } complete: { [unowned self] document, text, error in
- if error == nil {
- self.itemSuccess(item: item)
- } else {
- self.itemFailure(item: item, error: error! as NSError)
- }
-
- if i == filesData.count - 1 {
- self.batchSuccess()
- }
- }
- }
- }
- }
-
- func convertOCR(outputFolderPath: String,
- document: CPDFDocument,
- fileName: String,
- data: KMOCRModel,
- progress: @escaping KMOCRManagerOCRProgress,
- complete: @escaping KMOCRManagerOCRComplete) {
- //计算需要处理的页面
- let path = outputFolderPath + "/" + fileName + ".pdf"
- KMOCRManager.manager.convertBatchOCR(document: document, saveFilePath: path, model: data, progress: { [unowned self] progressValue in
- progress(progressValue)
- }) { [unowned self] document, text, error in
- complete(document, text, error)
- }
- }
-
- //MARK: 压缩
- func compressExport(data: KMBatchSettingItemViewModel, outputFolderPath: String) {
- self.compressFile(outputFolderPath: outputFolderPath, data: (data as? KMCompressSettingModel)!, filesData: self.batchFilesData)
- }
-
- func compressFile(outputFolderPath: String, data: KMCompressSettingModel, filesData: [KMBatchProcessingTableViewModel]) {
- if filesData.count != 0 {
- for i in 0..<filesData.count {
- let item = filesData[i]
- let document = CPDFDocument.init(url: URL(fileURLWithPath: item.filePath))
- if document != nil {
- let path = self.fetchFilePath(type: .compress, filePath: item.filePath, outputFolderPath: outputFolderPath)
-
- KMCompressManager.shared.compress(documentURL: URL(fileURLWithPath: item.filePath), fileURL: URL(fileURLWithPath: path), limit: false, model: data) { currentPage, totalPages in
- let progress = Float(currentPage) / Float(totalPages)
- self.itemProgress(item: item, processValue: progress)
- } cancelHandler: {
- return false
- } completionHandler: { [unowned self] isFinish in
- if isFinish {
- self.itemSuccess(item: item)
- } else {
- self.itemFailure(item: item, error: nil)
- }
-
- if i == filesData.count - 1 {
- self.batchSuccess()
- }
- }
- }
-
- }
- }
- }
-
- //MARK: 安全
- func securityExport(data: KMBatchSettingItemViewModel, outputFolderPath: String) {
- self.securityFile(outputFolderPath: outputFolderPath, data: data as! KMBatchSecurityViewModel, filesData: self.batchFilesData)
- }
-
- func securityFile(outputFolderPath: String, data: KMBatchSecurityViewModel, filesData: [KMBatchProcessingTableViewModel]) {
- if filesData.count != 0 {
- for i in 0..<filesData.count {
- let item = filesData[i]
- let docuemt = CPDFDocument.init(url: URL(fileURLWithPath: item.filePath))
- if (docuemt != nil) {
- let path = self.fetchFilePath(type: .security, filePath: item.filePath, outputFolderPath: outputFolderPath)
-
- var options: [CPDFDocumentWriteOption : Any] = [:]
- //开启密码
- if data.isOpenPassword &&
- !data.openPasswordString.isEmpty {
- options.updateValue(data.openPasswordString, forKey: .userPasswordOption)
- }
- //
- //权限密码
- if data.isPermission &&
- !data.permissionString.isEmpty {
- options.updateValue(data.permissionString, forKey: .ownerPasswordOption)
- }
-
- // 限制打印
- if data.restrictOptions.contains(.print) {
- options.updateValue(false, forKey: .allowsPrintingOption)
- } else {
- options.updateValue(true, forKey: .allowsPrintingOption)
- }
-
- //限制复制
- if data.restrictOptions.contains(.copy) {
- options.updateValue(false, forKey: .allowsCopyingOption)
- } else {
- options.updateValue(true, forKey: .allowsCopyingOption)
- }
-
-
- let result = docuemt!.write(toFile: path, withOptions: options)
- // let result = docuemt!.write(to: URL(fileURLWithPath: path), withOptions: options)
- if result {
- KMPrint("成功")
- self.itemSuccess(item: item)
- } else {
- KMPrint("失败")
- self.itemFailure(item: item, error: nil)
- }
-
- if i == filesData.count - 1 {
- self.batchSuccess()
- }
- }
- }
- }
- }
-
- //MARK: 水印
- func waterMarkApplay(data: KMBatchSettingItemViewModel, outputFolderPath: String) {
- if let data = data as? KMBatchWatermarkModel {
- self.waterMarkFile(outputFolderPath: outputFolderPath, data: data, filesData: self.batchFilesData)
- }
- }
-
- func waterMarkFile(outputFolderPath: String, data: KMBatchWatermarkModel, filesData: [KMBatchProcessingTableViewModel]) {
- if filesData.count != 0 {
- for i in 0..<filesData.count {
- let item = filesData[i]
- let path = self.fetchFilePath(type: .watermark, filePath: item.filePath, outputFolderPath: outputFolderPath)
- let document = CPDFDocument.init(url: URL(fileURLWithPath: item.filePath))
- if (document?.allowsPrinting == false || document?.allowsCopying == false) {
- let alert = NSAlert()
- alert.alertStyle = .critical
- alert.messageText = "此文档不允许修改"
- alert.runModal()
- return
- }
-
- if let watermarks = document?.watermarks(), let model = data.watermarkModel, let document = document {
- let pageString = self.fetchValidPageIndexString(document, model: item)
- let watermark = KMWatermarkModel.returnWaterMarkWith(model, document)
- watermark.pageString = pageString
- document.addWatermark(watermark)
- }
-
- if (FileManager.default.fileExists(atPath: path)) {
- try?FileManager.default.removeItem(atPath: path)
- }
-
- let result = document?.write(to: URL(fileURLWithPath: path)) ?? false
- if (result) {
- KMPrint("removeFile成功")
- self.itemSuccess(item: item)
- } else {
- KMPrint("removeFile失败")
- self.itemFailure(item: item, error: nil)
- }
- if i == filesData.count - 1 {
- self.batchSuccess()
- }
- }
- }
- }
-
- //MARK: 背景
- func backgroundApplay(data: KMBatchSettingItemViewModel, outputFolderPath: String) {
- if let data = data as? KMBatchBackgroundModel {
- self.backgroundFile(outputFolderPath: outputFolderPath, data: data, filesData: self.batchFilesData)
- }
- }
-
- func backgroundFile(outputFolderPath: String, data: KMBatchBackgroundModel, filesData: [KMBatchProcessingTableViewModel]) {
- if filesData.count != 0 {
- for i in 0..<filesData.count {
- let item = filesData[i]
- let path = self.fetchFilePath(type: .background, filePath: item.filePath, outputFolderPath: outputFolderPath)
- let document = CPDFDocument.init(url: URL(fileURLWithPath: item.filePath))
- if (document?.allowsPrinting == false || document?.allowsCopying == false) {
- let alert = NSAlert()
- alert.alertStyle = .critical
- alert.messageText = "此文档不允许修改"
- alert.runModal()
- return
- }
-
- if let background = document?.background(), let model = data.backgroundModel, let document = document {
- KMBackgroundManager.defaultManager.updateBackground(background, withModel: model)
-
- let pageIndexString = self.fetchValidPageIndexString(document, model: item)
-
- background.pageString = pageIndexString
- background.update()
-
- }
-
- if (FileManager.default.fileExists(atPath: path)) {
- try?FileManager.default.removeItem(atPath: path)
- }
-
- let result = document?.write(to: URL(fileURLWithPath: path)) ?? false
- if (result) {
- KMPrint("removeFile成功")
- self.itemSuccess(item: item)
- } else {
- KMPrint("removeFile失败")
- self.itemFailure(item: item, error: nil)
- }
- if i == filesData.count - 1 {
- self.batchSuccess()
- }
- }
- }
- }
-
- //MARK: 页眉页脚
- func headAndFooterApplay(data: KMBatchSettingItemViewModel, outputFolderPath: String) {
- if let data = data as? KMBatchHeaderAndFooterModel {
- self.headAndFooterFile(outputFolderPath: outputFolderPath, data: data, filesData: self.batchFilesData)
- }
- }
-
- func headAndFooterFile(outputFolderPath: String, data: KMBatchHeaderAndFooterModel, filesData: [KMBatchProcessingTableViewModel]) {
- if filesData.count != 0 {
- for i in 0..<filesData.count {
- let item = filesData[i]
- let path = self.fetchFilePath(type: .headerAndFooter, filePath: item.filePath, outputFolderPath: outputFolderPath)
- let document = CPDFDocument.init(url: URL(fileURLWithPath: item.filePath))
- if (document?.allowsPrinting == false || document?.allowsCopying == false) {
- let alert = NSAlert()
- alert.alertStyle = .critical
- alert.messageText = "此文档不允许修改"
- alert.runModal()
- return
- }
-
- if let headerFooter = document?.headerFooter(), let model = data.headerFooterModel, let document = document {
- let pageString = self.fetchValidPageIndexString(document, model: item)
- KMHeaderFooterManager.defaultManager.updateCPDFHeaderFooter(headerFooter, withModel: model, Int(document.pageCount))
- headerFooter.pageString = pageString
- headerFooter.update()
- }
-
- if (FileManager.default.fileExists(atPath: path)) {
- try?FileManager.default.removeItem(atPath: path)
- }
-
- let result = document?.write(to: URL(fileURLWithPath: path)) ?? false
- if (result) {
- KMPrint("removeFile成功")
- self.itemSuccess(item: item)
- } else {
- KMPrint("removeFile失败")
- self.itemFailure(item: item, error: nil)
- }
- if i == filesData.count - 1 {
- self.batchSuccess()
- }
- }
- }
- }
-
- //MARK: 贝茨码
- func batesApplay(data: KMBatchSettingItemViewModel, outputFolderPath: String) {
- if let data = data as? KMBatchBatesModel {
- self.batesFile(outputFolderPath: outputFolderPath, data: data, filesData: self.batchFilesData)
- }
- }
-
- func batesFile(outputFolderPath: String, data: KMBatchBatesModel, filesData: [KMBatchProcessingTableViewModel]) {
- if filesData.count != 0 {
- for i in 0..<filesData.count {
- let item = filesData[i]
- let path = self.fetchFilePath(type: .batesNumber, filePath: item.filePath, outputFolderPath: outputFolderPath)
- let document = CPDFDocument.init(url: URL(fileURLWithPath: item.filePath))
- if (document?.allowsPrinting == false || document?.allowsCopying == false) {
- let alert = NSAlert()
- alert.alertStyle = .critical
- alert.messageText = "此文档不允许修改"
- alert.runModal()
- return
- }
-
- if let bates = document?.bates(), let model = data.batesModel, let document = document {
- let pageString = self.fetchValidPageIndexString(document, model: item)
- KMBatesManager.defaultManager.updateCPDFBates(bates, withModel: model, Int(document.pageCount))
- bates.pageString = pageString
- bates.update()
- }
-
- if (FileManager.default.fileExists(atPath: path)) {
- try?FileManager.default.removeItem(atPath: path)
- }
-
- let result = document?.write(to: URL(fileURLWithPath: path)) ?? false
- if (result) {
- KMPrint("removeFile成功")
- self.itemSuccess(item: item)
- } else {
- KMPrint("removeFile失败")
- self.itemFailure(item: item, error: nil)
- }
- if i == filesData.count - 1 {
- self.batchSuccess()
- }
- }
- }
- }
-
- //MARK: 移除
- func removeApplay(data: KMBatchSettingItemViewModel, outputFolderPath: String) {
- self.removeFile(outputFolderPath: outputFolderPath, data: data as! KMBatchRemoveViewModel, filesData: self.batchFilesData)
- }
-
- func removeFile(outputFolderPath: String, data: KMBatchRemoveViewModel, filesData: [KMBatchProcessingTableViewModel]) {
- if filesData.count != 0 {
- for i in 0..<filesData.count {
- let item = filesData[i]
- // DispatchQueue.global().async {
- let path = self.fetchFilePath(type: .batchRemove, filePath: item.filePath, outputFolderPath: outputFolderPath)
- let document = CPDFDocument.init(url: URL(fileURLWithPath: item.filePath))
- if document != nil {
- if (document!.allowsPrinting == false || document!.allowsCopying == false) {
- let alert = NSAlert()
- alert.alertStyle = .critical
- alert.messageText = "此文档不允许修改"
- alert.runModal()
- return
- }
-
- if (data.options.contains(.security)) {
-
- }
-
- if (data.options.contains(.batesNumber)) {
- let property = document!.bates()
- property?.clear()
- }
- if (data.options.contains(.headerAndFooter)) {
- let property = document!.headerFooter()
- property?.clear()
- }
- if (data.options.contains(.background)) {
- let property = document!.background()
- property?.clear()
- }
- if (data.options.contains(.watermark)) {
- let array: Array<CPDFWatermark> = document!.watermarks() ?? []
- for model in array {
- document!.removeWatermark(model)
- }
- }
-
- if (FileManager.default.fileExists(atPath: path)) {
- try?FileManager.default.removeItem(atPath: path)
- }
-
- let result = document!.write(to: URL(fileURLWithPath: path))
- if (result) {
- KMPrint("removeFile成功")
- self.itemSuccess(item: item)
- } else {
- KMPrint("removeFile失败")
- self.itemFailure(item: item, error: nil)
- }
- if i == filesData.count - 1 {
- self.batchSuccess()
- }
- }
- // }
- }
- }
- }
-
- //MARK: 图片转PDF
- func imageToPDFExport(data: KMBatchSettingItemViewModel, outputFolderPath: String) {
- self.imageToPDFFile(outputFolderPath: outputFolderPath, data: data as! KMBatchImageToPDFModel, filesData: self.batchFilesData)
- }
-
- func imageToPDFFile(outputFolderPath: String, data: KMBatchImageToPDFModel, filesData: [KMBatchProcessingTableViewModel]) {
- if filesData.count != 0 {
- self.batchProgress()
- if data.isNewPDF {
- if data.isMergeAll {
- let item = filesData[0]
- let path = self.fetchFilePath(type: .imageToPDF, filePath: item.filePath, outputFolderPath: outputFolderPath)
-
-
- let pdfDocument = CPDFDocument()
- for item in filesData {
- pdfDocument?.km_insert(image: item.image, at: pdfDocument?.pageCount ?? 0)
- }
-
- if data.isOCR {
- let model = KMOCRModel()
- model.showType = .page
- model.saveAsPDF = true
- model.ocrType = data.ocrType
- model.languageType = data.languageType
- model.needTxT = data.isExtractText
- model.pageRangeType = .all
-
- //计算需要处理的页面
- let pages:[Int] = KMOCRManager.fetchPageIndex(document: pdfDocument!, model: model)
- model.pageRange = pages
-
- self.batchProgress()
- self.convertOCR(outputFolderPath: outputFolderPath, document: pdfDocument!, fileName: path.deletingPathExtension.lastPathComponent, data: model) { progress in
- self.batchProgress()
- } complete: { document, text, error in
- self.batchSuccess()
- }
- } else {
- let success = pdfDocument?.write(toFile: path)
- if success != nil {
- for item in filesData {
- self.itemSuccess(item: item)
- }
- self.batchSuccess()
- } else {
- self.batchFailure()
- }
- }
- } else {
- processFile(at: 0, outputFolderPath: outputFolderPath, data: data)
- }
- } else {
- let selectFilePath = data.selectFilePath
- if selectFilePath.count == 0 {
- let alert = NSAlert()
- alert.alertStyle = .critical
- alert.messageText = KMLocalizedString("文件未选择")
- alert.runModal()
- return
- }
-
- var fileName = selectFilePath.deletingPathExtension.lastPathComponent
- let path = self.fetchFilePath(type: .imageToPDF, filePath: selectFilePath, outputFolderPath: outputFolderPath)
-
- var pdfDocument = CPDFDocument(url: NSURL(fileURLWithPath: selectFilePath) as URL)
- let count: Int = Int(pdfDocument?.pageCount ?? 0)
- for item in filesData {
- pdfDocument?.km_insert(image: item.image, at: UInt(count))
- }
-
- if data.isOCR {
- let model = KMOCRModel()
- model.showType = .page
- model.saveAsPDF = true
- model.ocrType = data.ocrType
- model.languageType = data.languageType
- model.needTxT = data.isExtractText
- model.pageRangeType = .all
- //计算需要处理的页面
- let pages:[Int] = KMOCRManager.fetchPageIndex(document: pdfDocument!, model: model)
- model.pageRange = pages
-
- self.convertOCR(outputFolderPath: outputFolderPath, document: pdfDocument!, fileName: fileName, data: model) { progress in
-
- } complete: { document, text, error in
- if (error != nil) {
- self.batchFailure()
- } else {
- for item in filesData {
- self.itemSuccess(item: item)
- }
- self.batchSuccess()
- }
- }
- } else {
- let success = pdfDocument?.write(toFile: path)
- if success != nil {
- for item in filesData {
- self.itemSuccess(item: item)
- }
- self.batchSuccess()
- } else {
- self.batchFailure()
- }
- }
- }
- }
- }
-
- func processFile(at index: Int, outputFolderPath: String, data: KMBatchImageToPDFModel) {
- guard index < filesData.count else {
- self.batchSuccess()
- return
- }
- let item = filesData[index]
- if data.isOCR {
- let path = self.fetchFilePath(type: .imageToPDF, filePath: item.filePath, outputFolderPath: outputFolderPath)
- let pdfDocument = CPDFDocument()
- pdfDocument?.km_insert(image: item.image, at: pdfDocument?.pageCount ?? 0)
- let model = KMOCRModel()
- model.showType = .page
- model.saveAsPDF = true
- model.ocrType = data.ocrType
- model.languageType = data.languageType
- model.needTxT = data.isExtractText
- model.pageRangeType = .all
- let pages: [Int] = KMOCRManager.fetchPageIndex(document: pdfDocument!, model: model)
- model.pageRange = pages
- self.itemProgress(item: item, processValue: 0)
- self.convertOCR(outputFolderPath: outputFolderPath, document: pdfDocument!, fileName: path.deletingPathExtension.lastPathComponent, data: model) { [unowned self] progress in
- self.itemProgress(item: item, processValue: progress)
- } complete: { [unowned self] document, text, error in
- self.itemSuccess(item: filesData[index])
- processFile(at: index + 1, outputFolderPath: outputFolderPath, data: data)
- }
- } else {
- let path = self.fetchFilePath(type: .imageToPDF, filePath: item.filePath, outputFolderPath: outputFolderPath)
- let pdfDocument = CPDFDocument()
- pdfDocument?.km_insert(image: item.image, at: pdfDocument?.pageCount ?? 0)
- let success = pdfDocument?.write(toFile: path)
- if success != nil {
- self.itemSuccess(item: item)
- processFile(at: index + 1, outputFolderPath: outputFolderPath, data: data)
- } else {
- self.itemFailure(item: item, error: nil)
- }
- }
- }
- }
- //MARK: private
- extension KMBatchManager {
- func fetchValidPageIndexString(_ document: CPDFDocument, model: KMBatchProcessingTableViewModel) -> String? {
- if model.pageRange == .all {
- let pages = Array(0..<Int(document.pageCount))
- let pageIndexString = pages.isEmpty ? "" : pages.map { "\($0)" }.joined(separator: ",")
-
- return pageIndexString
- } else {
- let data = KMOCRModel()
- data.pageRangeType = model.pageRange
- data.pageRangeString = model.pageRangeString
-
- let pages:[Int] = KMOCRManager.fetchPageIndex(document: document, model: data)
- let pageIndexString = pages.isEmpty ? "" : pages.map { "\($0)" }.joined(separator: ",")
-
- return pageIndexString
- }
- return nil
- }
-
- func fetchValidPageIndexs(_ document: CPDFDocument, model: KMBatchProcessingTableViewModel) -> [Int]? {
- if model.pageRange == .all {
- let pages = Array(0..<Int(document.pageCount))
- return pages
- } else {
- let data = KMOCRModel()
- data.pageRangeType = model.pageRange
- data.pageRangeString = model.pageRangeString
-
- let pages:[Int] = KMOCRManager.fetchPageIndex(document: document, model: data)
- return pages
- }
- return []
- }
-
- func fetchDocument(filePath: String, model: KMBatchProcessingTableViewModel) -> CPDFDocument {
- var document = CPDFDocument(url: URL(fileURLWithPath: filePath))
- if model.password.count != 0 {
- document?.unlock(withPassword: model.password)
- }
-
- if model.pageRange == .all {
-
- } else {
- let data = KMOCRModel()
- data.pageRangeType = model.pageRange
- data.pageRangeString = model.pageRangeString
-
- let pages:[Int] = KMOCRManager.fetchPageIndex(document: document!, model: data)
-
- var tempDocument = CPDFDocument()
- for i in 0..<pages.count {
- let page = document?.page(at: UInt(i))
- tempDocument?.insertPageObject(page, at: tempDocument?.pageCount ?? 0)
- }
-
- let fileName = filePath.deletingPathExtension.lastPathComponent
- let isSuccess = tempDocument?.write(toFile: self.fetchTempFilePath(fileName: fileName))
- if isSuccess != nil {
- document = tempDocument
- }
- }
-
- return document ?? CPDFDocument()
- }
-
- func fetchTempFilePath(fileName: String) -> String {
- let floderPath = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.applicationSupportDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).last?.stringByAppendingPathComponent(Bundle.main.bundleIdentifier!).stringByAppendingPathComponent("BatchTemp")
- let filePath = floderPath?.stringByAppendingPathComponent("\(fileName).pdf")
- if let data = floderPath, !FileManager.default.fileExists(atPath: data) {
- try?FileManager.default.createDirectory(atPath: data, withIntermediateDirectories: false)
- }
- if let data = filePath, !FileManager.default.fileExists(atPath: data) {
- FileManager.default.createFile(atPath: data, contents: nil)
- }
- return filePath ?? ""
- }
-
- func removeTempFilePath(filePath: String) {
- let fileName = filePath.deletingPathExtension.lastPathComponent
- let path = self.fetchTempFilePath(fileName: fileName)
-
- if (FileManager.default.fileExists(atPath: path)) {
- try?FileManager.default.removeItem(atPath: path)
- }
- }
-
- func fetchFilePath(type: KMBatchCollectionViewType, filePath: String, outputFolderPath: String) -> String {
- var fileName = filePath.deletingPathExtension.lastPathComponent
- if fileName.isEmpty {
- fileName = NSLocalizedString("Untitled", comment: "")
- }
- let path = outputFolderPath + "/" + fileName + ".pdf"
- // // 检查文件是否已存在,如果存在,则添加数字后缀
- // var finalPath = path
- // var count = 1
- // while FileManager.default.fileExists(atPath: finalPath) {
- // let newFileName = "\(fileName) \(count)"
- // finalPath = outputFolderPath + "/" + newFileName + ".pdf"
- // count += 1
- // }
- // 使用最终路径进行保存或其他操作
- // path = finalPath
-
- return path
- }
- }
- //MARK: Alert
- extension KMBatchManager {
- func batchUnkown() {
- self.state = .unknow
- NotificationCenter.default.post(name: NSNotification.Name(kBacthProcessNotification), object: nil)
- }
-
- func batchProgress() {
- for item in filesData {
- self.itemProgress(item: item, processValue: 0)
- }
-
- self.state = .processing
- NotificationCenter.default.post(name: NSNotification.Name(kBacthProcessNotification), object: nil)
- }
-
- func batchSuccess() {
- if FileManager.default.fileExists(atPath: self.outputFolderPath) {
- NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: self.outputFolderPath)])
- }
-
- self.state = .complete
- NotificationCenter.default.post(name: NSNotification.Name(kBacthProcessNotification), object: nil)
- }
-
- func batchFailure() {
- if FileManager.default.fileExists(atPath: self.outputFolderPath) {
- NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: self.outputFolderPath)])
- }
-
- self.state = .error
- NotificationCenter.default.post(name: NSNotification.Name(kBacthProcessNotification), object: nil)
- }
-
- func itemProgress(item: KMBatchProcessingTableViewModel, processValue: Float) {
- if processValue > 0.7 {
- item.state = .loading70
- } else {
- item.state = .loading
- }
- NotificationCenter.default.post(name: NSNotification.Name(kBacthFilesProcessNotification), object: item)
- }
-
- func itemSuccess(item: KMBatchProcessingTableViewModel) {
- self.removeTempFilePath(filePath: item.filePath)
- item.state = .success
- NotificationCenter.default.post(name: NSNotification.Name(kBacthFilesProcessNotification), object: item)
- }
-
- func itemFailure(item: KMBatchProcessingTableViewModel, error: NSError?) {
- self.removeTempFilePath(filePath: item.filePath)
- item.state = .error
- NotificationCenter.default.post(name: NSNotification.Name(kBacthFilesProcessNotification), object: item)
-
- guard let error = error else { return }
- var errorString = ""
- let myError: NSError = error as NSError
- if myError.code == 1 {
- errorString = NSLocalizedString("Password required or incorrect password. Please re-enter your password and try again", comment: "")
- } else if myError.code == 2 {
- errorString = NSLocalizedString("The license doesn't allow the permission", comment: "")
- } else if myError.code == 3 {
- errorString = NSLocalizedString("Malloc failure", comment: "")
- } else if myError.code == 4 {
- errorString = NSLocalizedString("Unknown error in processing conversion. Please try again later", comment: "")
- } else if myError.code == 5 {
- errorString = NSLocalizedString("Unknown error in processing PDF. Please try again later", comment: "")
- } else if myError.code == 6 {
- errorString = NSLocalizedString("File not found or could not be opened. Check if your file exists or choose another file to convert", comment: "")
- } else if myError.code == 7 {
- errorString = NSLocalizedString("File not in PDF format or corruptead. Change a PDF file and try again", comment: "")
- } else if myError.code == 8 {
- errorString = NSLocalizedString("Unsupported security scheme", comment: "")
- } else if myError.code == 9 {
- errorString = NSLocalizedString("Page not found or content error", comment: "")
- } else if myError.code == 404 {
- errorString = NSLocalizedString("Please check if the information is wrong or the network is error.", comment: "")
- } else {
- errorString = NSLocalizedString("Table not found", comment: "")
- }
-
- let alert = NSAlert()
- alert.alertStyle = .critical
- alert.messageText = NSLocalizedString("Conversion Failed", comment: "")
- alert.informativeText = errorString
- alert.addButton(withTitle: NSLocalizedString("OK", comment: ""))
- alert.runModal()
- }
- }
|