FileConverter.swift 15 KB

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