FileConverter.swift 17 KB

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