FileConverter.swift 16 KB

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