FileConverter.swift 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422
  1. //
  2. // FileConverter.swift
  3. // KdanAuto
  4. //
  5. // Created by 朱东勇 on 2022/12/21.
  6. //
  7. import Foundation
  8. import ComPDFKit_Conversion
  9. import PDFKit
  10. let KMComPDFKit_Conversion_FreeKey = "hw5vIMzKU2Im6cPijLjG45VAHy01ikUF5/GdAMdzCV8n2QTKNN0d8kG8crVbGYjIMsvVP+A9gx5g+W8qEi4ho0YTkGDratHOrX68W7khEBHAv7OEyRxIhlhBmdEQD+21lsRpIEW5zucUAF231lo3ZZiiT2s9CualDQJdAo1G0DI=";
  11. let KMComPDFKit_Conversion_FreeSecret = "mG0c3O3Mzeu5dkZJW3gpqh188cTuhYlGRPrbR/gfX4p9ms/F1zY6gZ1RBu8mNJH8zLwqe9EJswNmwV09TNi2IiIDeG7Ulx+U4pbeFB3/eYl2J6LePb3Kl54OsKlYiaf3Mv7C2jvq4o0q6sQtN3jR4897KG6mIUGJSRuOsvjYroVgMwna6EUx0K0SBmBGoFYDYkwcNWVMyYvggPV2rTFvfawopGIC034QzjthmhwwX90=";
  12. let KMPDFConvertOptionsKeyImageDPI = "KMPDFConvertOptionsKeyImageDPI"
  13. let KMPDFConvertOptionsKeyImageWithAnnotation = "KMPDFConvertOptionsKeyImageWithAnnotation"
  14. let kDefaultPassword = "666666"
  15. class FileConverter : NSObject, CPDFConverterDelegate, CPDFConverterFPToolDelegate
  16. {
  17. var pdfConverter:CPDFConverter?
  18. var fpConverter:AnyObject?
  19. var options:CPDFConvertOptions?
  20. var originSrcPath:String = ""
  21. var srcPath:String = ""
  22. var desPath:String = ""
  23. var pages:[Int] = []
  24. var pathExtension = ""
  25. var convertQueue = DispatchQueue.main
  26. var semaphore:DispatchSemaphore? = DispatchSemaphore.init(value: 0)
  27. var accessSemaphore:DispatchSemaphore? = DispatchSemaphore.init(value: 1)
  28. var didSuccess:Int = 1
  29. let m_currentVersion = CPDFConvertKit.sharedInstance().buildNumber
  30. var complention = { (status:Int) in
  31. }
  32. static var instance = FileConverter()
  33. class func shared() -> FileConverter {
  34. return instance
  35. }
  36. func converter(_ inSrcPath: String, inDesPath: String, complention:@escaping (_ status:Int) -> ()) {
  37. return converter(inSrcPath, inDesPath: inDesPath, params: nil, complention: complention)
  38. }
  39. func converter(_ inSrcPath: String, inDesPath: String, params:NSDictionary?, complention:@escaping (_ status:Int) -> ()) {
  40. self.complention = complention;
  41. if !FileManager.default.fileExists(atPath: inSrcPath) {
  42. self.complention(-1)
  43. return
  44. }
  45. self.originSrcPath = inSrcPath;
  46. self.srcPath = inSrcPath
  47. self.desPath = inDesPath
  48. if FileManager.default.fileExists(atPath: desPath) {
  49. try? FileManager.default.removeItem(atPath: desPath)
  50. }
  51. let directory = NSString(string: desPath).deletingLastPathComponent
  52. if !FileManager.default.fileExists(atPath: directory) {
  53. try? FileManager.default.createDirectory(atPath: directory, withIntermediateDirectories: true)
  54. }
  55. let attributy = try! FileManager.default.attributesOfItem(atPath: srcPath)
  56. let fileType = attributy[FileAttributeKey.type] as! FileAttributeType
  57. if NSString(string: FileAttributeType.typeSymbolicLink.rawValue).isEqual(to: fileType.rawValue) {
  58. let symbolicLink = try? FileManager.default.destinationOfSymbolicLink(atPath: self.srcPath)
  59. if nil != symbolicLink {
  60. self.srcPath = symbolicLink!
  61. }
  62. }
  63. if FileManager.default.fileExists(atPath: self.desPath) {
  64. try? FileManager.default.removeItem(atPath: self.desPath)
  65. }
  66. self.pathExtension = NSString(string: self.desPath).pathExtension
  67. // let outputPath = NSString(string: self.desPath).deletingPathExtension
  68. // let output = self.desPath
  69. let password = params?.value(forKey: "password")
  70. let tParams = params ?? [:]
  71. let useOldLibValue = params?.value(forKey: "useOldLib")
  72. var useOldLib = false;
  73. if (nil != useOldLibValue) {
  74. if ((useOldLibValue as? String) != nil) {
  75. useOldLib = NSArray(array: ["TRUE", "true", "1"]).contains((useOldLibValue as! String))
  76. }else if ((useOldLibValue as? NSNumber) != nil) {
  77. useOldLib = (useOldLibValue as? NSNumber)!.boolValue || (useOldLibValue as? NSNumber)!.intValue == 1
  78. }
  79. }
  80. // NSLog("%@ - %@\n\(inSrcPath)", useOldLib ? "老库" : "新库", params ?? "")
  81. self.convertQueue.async {
  82. if (LogViewController.shared().isVisable()) {
  83. LogViewController.shared().appendLog("\n转档:\(NSString(string: inSrcPath).lastPathComponent)\n")
  84. }
  85. let url = URL.init(fileURLWithPath: self.srcPath, isDirectory: false)
  86. let document = PDFDocument(url: url)
  87. if document == nil {
  88. self.didSuccess = -2;
  89. self.complention(self.didSuccess)
  90. self.accessSemaphore?.signal()
  91. return
  92. }
  93. let pageCount = document!.pageCount
  94. self.pages = []
  95. for i in 1...pageCount {
  96. self.pages.append(i)
  97. }
  98. if !useOldLib && NSArray(array: ["jpg", "JPG", "png", "PNG"]).contains(self.pathExtension) {
  99. autoreleasepool {
  100. let cachePath = NSString(string: self.desPath).deletingPathExtension+".zip"
  101. self.pdfConverter = CPDFConverterImg.init(url: url, password: nil)
  102. if (nil == self.pdfConverter && nil != password) {
  103. self.pdfConverter = CPDFConverterImg.init(url: url, password: password as? String)
  104. }
  105. self.pdfConverter?.delegate = self
  106. self.options = CPDFConvertImgOptions()
  107. var fileType = "JPG"
  108. if (NSArray(array: ["jpg", "JPG"]).contains(self.pathExtension)) {
  109. (self.options as! CPDFConvertImgOptions).type = .JPEG
  110. }else {
  111. (self.options as! CPDFConvertImgOptions).type = .PNG
  112. fileType = "PNG"
  113. }
  114. self.configForOptions(self.options, inParams: tParams);
  115. self.showLog(self.options, fileType: fileType)
  116. do {
  117. try? self.pdfConverter?.convert(toFilePath: cachePath, pageIndexs: self.pages, options: self.options)
  118. }catch {
  119. self.didSuccess = -1;
  120. self.complention(self.didSuccess)
  121. self.accessSemaphore?.signal()
  122. }
  123. }
  124. }else if !useOldLib && NSArray(array: ["ppt", "PPT", "PPTX", "pptx"]).contains(self.pathExtension) {
  125. autoreleasepool {
  126. self.pdfConverter = CPDFConverterPPT.init(url: url, password: nil)
  127. if (nil == self.pdfConverter && nil != password) {
  128. self.pdfConverter = CPDFConverterPPT.init(url: url, password: password as? String)
  129. }
  130. self.pdfConverter?.delegate = self
  131. self.options = CPDFConvertPPTOptions()
  132. self.configForOptions(self.options, inParams: tParams);
  133. self.showLog(self.options, fileType: "PPT")
  134. self.pdfConverter?.convert(toFilePath: self.desPath,
  135. pageIndexs: self.pages, options: self.options)
  136. }
  137. }else if !useOldLib && NSArray(array: ["doc", "DOC", "docx", "DOCX"]).contains(self.pathExtension) {
  138. autoreleasepool {
  139. self.pdfConverter = CPDFConverterWord.init(url: url, password: nil)
  140. if (nil == self.pdfConverter && nil != password) {
  141. self.pdfConverter = CPDFConverterWord.init(url: url, password: password as? String)
  142. }
  143. self.pdfConverter?.delegate = self
  144. self.options = CPDFConvertWordOptions()
  145. self.configForOptions(self.options, inParams: tParams);
  146. self.showLog(self.options, fileType: "Word")
  147. self.pdfConverter?.convert(toFilePath: self.desPath,
  148. pageIndexs: self.pages, options: self.options)
  149. }
  150. }else if !useOldLib && NSArray(array: ["xls", "XLS", "xlsx", "XLSX"]).contains(self.pathExtension) {
  151. autoreleasepool {
  152. self.pdfConverter = CPDFConverterExcel.init(url: url, password: nil)
  153. if (nil == self.pdfConverter && nil != password) {
  154. self.pdfConverter = CPDFConverterExcel.init(url: url, password: password as? String)
  155. }
  156. self.pdfConverter?.delegate = self
  157. self.options = CPDFConvertExcelOptions()
  158. self.configForOptions(self.options, inParams: tParams);
  159. self.showLog(self.options, fileType: "Excel")
  160. self.pdfConverter?.convert(toFilePath: self.desPath,
  161. pageIndexs: self.pages, options: self.options)
  162. }
  163. }else if !useOldLib && NSArray(array: ["csv", "CSV"]).contains(self.pathExtension) {
  164. autoreleasepool {
  165. let cachePath = NSString(string: self.desPath).deletingPathExtension+".zip"
  166. self.pdfConverter = CPDFConverterCsv.init(url: url, password: nil)
  167. if (nil == self.pdfConverter && nil != password) {
  168. self.pdfConverter = CPDFConverterCsv.init(url: url, password: password as? String)
  169. }
  170. self.pdfConverter?.delegate = self
  171. self.options = CPDFConvertCsvOptions()
  172. self.configForOptions(self.options, inParams: tParams);
  173. self.showLog(self.options, fileType: "CSV")
  174. self.pdfConverter?.convert(toFilePath: cachePath,
  175. pageIndexs: self.pages, options: self.options)
  176. }
  177. }else if !useOldLib && NSArray(array: ["html", "HTML"]).contains(self.pathExtension) {
  178. autoreleasepool {
  179. let cachePath = NSString(string: self.desPath).deletingPathExtension+".zip"
  180. self.pdfConverter = CPDFConverterHtml.init(url: url, password: nil)
  181. if (nil == self.pdfConverter && nil != password) {
  182. self.pdfConverter = CPDFConverterHtml.init(url: url, password: password as? String)
  183. }
  184. self.pdfConverter?.delegate = self
  185. self.options = CPDFConvertHtmlOptions()
  186. self.configForOptions(self.options, inParams: tParams);
  187. self.showLog(self.options, fileType: "HTML")
  188. self.pdfConverter?.convert(toFilePath: cachePath,
  189. pageIndexs: self.pages, options: self.options)
  190. }
  191. }else if !useOldLib && NSArray(array: ["rtf", "RTF"]).contains(self.pathExtension) {
  192. autoreleasepool {
  193. self.pdfConverter = CPDFConverterRtf.init(url: url, password: nil)
  194. if (nil == self.pdfConverter && nil != password) {
  195. self.pdfConverter = CPDFConverterRtf.init(url: url, password: password as? String)
  196. }
  197. self.pdfConverter?.delegate = self
  198. self.options = CPDFConvertRtfOptions()
  199. self.configForOptions(self.options, inParams: tParams);
  200. self.showLog(self.options, fileType: "RTF")
  201. self.pdfConverter?.convert(toFilePath: self.desPath,
  202. pageIndexs: self.pages, options: self.options)
  203. }
  204. }else if !useOldLib && NSArray(array: ["txt", "TXT"]).contains(self.pathExtension) {
  205. autoreleasepool {
  206. self.pdfConverter = CPDFConverterTxt.init(url: url, password: nil)
  207. if (nil == self.pdfConverter && nil != password) {
  208. self.pdfConverter = CPDFConverterTxt.init(url: url, password: password as? String)
  209. }
  210. self.pdfConverter?.delegate = self
  211. self.options = CPDFConvertTxtOptions()
  212. self.configForOptions(self.options, inParams: tParams);
  213. self.showLog(self.options, fileType: "TXT")
  214. self.pdfConverter?.convert(toFilePath: self.desPath,
  215. pageIndexs: self.pages, options: self.options)
  216. }
  217. }else {
  218. autoreleasepool {
  219. let className = "CPDFConverterFP"
  220. let cl = NSClassFromString(className)
  221. if (nil == cl) {
  222. self.complention(-1)
  223. self.accessSemaphore?.signal()
  224. }else {
  225. if self.fpConverter == nil {
  226. self.fpConverter = CPDFConverterFPTool.createConverterFP() as AnyObject
  227. CPDFConverterFPTool.setDelegate(self, forConverterFP: self.fpConverter)
  228. }else {
  229. CPDFConverterFPTool.stopConvertsionIfNeed(self.fpConverter)
  230. }
  231. var needMerge = NSArray(array: ["csv", "CSV"]).contains(self.pathExtension)
  232. let dpi = tParams.value(forKey: "KMPDFConvertOptionsKeyImageDPI")
  233. if (needMerge && tParams.value(forKey: "CPDFConvertOptionsKeyAllInOneSheet") != nil) {
  234. needMerge = (tParams.value(forKey: "CPDFConvertOptionsKeyAllInOneSheet") as! NSNumber).boolValue
  235. }
  236. if (LogViewController.shared().isVisable()) {
  237. LogViewController.shared().appendLog("转档参数\n")
  238. LogViewController.shared().appendLog("- 库版本: 老库\n")
  239. let options = [
  240. "KMPDFConvertOptionsKeyImageDPI" : (dpi as? String) ?? "72",
  241. "CPDFConvertOptionsKeyAllInOneSheet":NSNumber(booleanLiteral: needMerge)
  242. ]
  243. LogViewController.shared().appendLog("- 其它参数:\(options)\n")
  244. }
  245. CPDFConverterFPTool.convertPDF(forConverterFP: self.fpConverter,
  246. path: self.srcPath,
  247. pdfPassword: password as? String,
  248. pdfPageIndexs: self.pages,
  249. destDocType: self.pathExtension,
  250. destDocPath: self.desPath,
  251. moreOptions: [
  252. "KMPDFConvertOptionsKeyImageDPI" : (dpi as? String) ?? "72",
  253. "CPDFConvertOptionsKeyAllInOneSheet":NSNumber(booleanLiteral: needMerge)
  254. ])
  255. }
  256. }
  257. }
  258. }
  259. }
  260. func converter(_ inSrcPath: String, inDesPath: String) -> Int {
  261. return converter(inSrcPath, inDesPath: inDesPath, params: nil)
  262. }
  263. func converter(_ inSrcPath: String, inDesPath: String, params:NSDictionary?) -> Int {
  264. if !FileManager.default.fileExists(atPath: inSrcPath) {
  265. return -1
  266. }
  267. accessSemaphore?.wait()
  268. converter(inSrcPath, inDesPath: inDesPath, params: params) { status in
  269. self.semaphore?.signal()
  270. };
  271. semaphore?.wait()
  272. accessSemaphore?.signal()
  273. return didSuccess
  274. }
  275. /// CPDFConverterDelegate
  276. func converter(_ converter: CPDFConverter!, didStartConvert error: Error!) {
  277. didSuccess = 0;
  278. }
  279. func converter(_ converter: CPDFConverter!, didEndConvert error: Error!) {
  280. didSuccess = nil == error ? 1 : 0
  281. Thread.sleep(forTimeInterval: 0.1)
  282. autoreleasepool {
  283. if NSArray(array: ["jpg", "JPG", "png", "PNG", "HTML", "html", "csv", "CSV"]).contains(self.pathExtension) {
  284. let cachePath = NSString(string: self.desPath).deletingPathExtension+".zip"
  285. let zip = ZipArchive.init()
  286. if (zip.unzipOpenFile(cachePath) && zip.unzipFile(to: self.desPath, overWrite: true)) {
  287. try? FileManager.default.removeItem(atPath: cachePath)
  288. }else {
  289. try? FileManager.default.moveItem(atPath: cachePath,
  290. toPath: self.desPath)
  291. }
  292. }
  293. if self.pdfConverter?.isConverting == true {
  294. self.pdfConverter?.cancel()
  295. }
  296. self.pdfConverter?.delegate = nil
  297. self.pdfConverter = nil
  298. self.complention(didSuccess)
  299. }
  300. }
  301. func converter(_ converter: CPDFConverter!, pageIndex index: UInt, pageCount count: UInt) {
  302. }
  303. /// CPDFConverterFPDelegate
  304. func fppdfConverter(_ converter: Any!, didEndConversion error: Error!) {
  305. autoreleasepool {
  306. didSuccess = nil == error ? 1 : 0
  307. CPDFConverterFPTool.stopConvertsionIfNeed(self.fpConverter)
  308. self.fpConverter = nil;
  309. Thread.sleep(forTimeInterval: 0.3)
  310. self.complention(didSuccess)
  311. }
  312. }
  313. /// Cancel
  314. func cancelTask() {
  315. if (self.fpConverter != nil) {
  316. CPDFConverterFPTool.stopConvertsionIfNeed(self.fpConverter)
  317. self.fpConverter = nil;
  318. Thread.sleep(forTimeInterval: 0.3)
  319. }
  320. if (self.pdfConverter != nil) {
  321. self.pdfConverter?.delegate = nil
  322. if self.pdfConverter?.isConverting == true {
  323. self.pdfConverter?.cancel()
  324. }
  325. self.pdfConverter = nil
  326. Thread.sleep(forTimeInterval: 0.3)
  327. self.complention(didSuccess)
  328. }
  329. }
  330. func cancelTaskForSrcPath(_ srcPath:String) {
  331. if (NSString(string: srcPath).isEqual(to: self.originSrcPath)) {
  332. cancelTask();
  333. }
  334. }
  335. // Config Options Tools
  336. func configForOptions(_ inOptions:CPDFConvertOptions?, inParams:NSDictionary?) {
  337. // Fetch Options Info
  338. let params = NSArray(array: (inParams?.value(forKey: "Options") as? [NSDictionary] ?? []))
  339. // options is not empty or nil
  340. for param in params {
  341. PerformSelectTool.performSelector(inOptions as Any, params: param as! [AnyHashable : Any]);
  342. }
  343. }
  344. // Show Options
  345. func showLog(_ options:CPDFConvertOptions?, fileType:String) {
  346. if (LogViewController.shared().isVisable()) {
  347. LogViewController.shared().appendLog("[\(fileType)]转档参数\n")
  348. LogViewController.shared().appendLog("- 库版本: 新库\n")
  349. let info = AdvanceSettingViewController.baseInfoFor(fileType)
  350. let paramStrings = PerformSelectTool.paramsLog(with: options!, paramRules: info as! [AnyHashable : Any])
  351. for string in paramStrings {
  352. LogViewController.shared().appendLog("- \(string as! String)\n")
  353. }
  354. }
  355. }
  356. }