FileConverter.swift 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  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("%@ - %@\n\(inSrcPath)", 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. if (params != nil) {
  105. if let dipValue = params!["imageDpi"] as? NSNumber {
  106. if (CPDFConvertKit.sharedInstance().buildNumber >= 150) {
  107. try? (self.options as! CPDFConvertImgOptions).imageDpi = Int32(dipValue.intValue)
  108. }
  109. }
  110. }
  111. self.pdfConverter?.convert(toFilePath: cachePath, pageIndexs: self.pages, options: self.options)
  112. }
  113. }else if !useOldLib && NSArray(array: ["ppt", "PPT", "PPTX", "pptx"]).contains(self.pathExtension) {
  114. autoreleasepool {
  115. self.pdfConverter = CPDFConverterPPT.init(url: url, password: nil)
  116. if (nil == self.pdfConverter && nil != password) {
  117. self.pdfConverter = CPDFConverterPPT.init(url: url, password: password as? String)
  118. }
  119. self.pdfConverter?.delegate = self
  120. self.options = CPDFConvertPPTOptions()
  121. self.pdfConverter?.convert(toFilePath: self.desPath,
  122. pageIndexs: self.pages, options: self.options)
  123. }
  124. }else if !useOldLib && NSArray(array: ["doc", "DOC", "docx", "DOCX"]).contains(self.pathExtension) {
  125. autoreleasepool {
  126. self.pdfConverter = CPDFConverterWord.init(url: url, password: nil)
  127. if (nil == self.pdfConverter && nil != password) {
  128. self.pdfConverter = CPDFConverterWord.init(url: url, password: password as? String)
  129. }
  130. self.pdfConverter?.delegate = self
  131. self.options = CPDFConvertWordOptions()
  132. self.pdfConverter?.convert(toFilePath: self.desPath,
  133. pageIndexs: self.pages, options: self.options)
  134. }
  135. }else if !useOldLib && NSArray(array: ["xls", "XLS", "xlsx", "XLSX"]).contains(self.pathExtension) {
  136. autoreleasepool {
  137. self.pdfConverter = CPDFConverterExcel.init(url: url, password: nil)
  138. if (nil == self.pdfConverter && nil != password) {
  139. self.pdfConverter = CPDFConverterExcel.init(url: url, password: password as? String)
  140. }
  141. self.pdfConverter?.delegate = self
  142. self.options = CPDFConvertExcelOptions()
  143. self.pdfConverter?.convert(toFilePath: self.desPath,
  144. pageIndexs: self.pages, options: self.options)
  145. }
  146. }else if !useOldLib && NSArray(array: ["csv", "CSV"]).contains(self.pathExtension) {
  147. autoreleasepool {
  148. let cachePath = NSString(string: self.desPath).deletingPathExtension+".zip"
  149. self.pdfConverter = CPDFConverterCsv.init(url: url, password: nil)
  150. if (nil == self.pdfConverter && nil != password) {
  151. self.pdfConverter = CPDFConverterCsv.init(url: url, password: password as? String)
  152. }
  153. self.pdfConverter?.delegate = self
  154. self.options = CPDFConvertCsvOptions()
  155. self.pdfConverter?.convert(toFilePath: cachePath,
  156. pageIndexs: self.pages, options: self.options)
  157. }
  158. }else if !useOldLib && NSArray(array: ["html", "HTML"]).contains(self.pathExtension) {
  159. autoreleasepool {
  160. let cachePath = NSString(string: self.desPath).deletingPathExtension+".zip"
  161. self.pdfConverter = CPDFConverterHtml.init(url: url, password: nil)
  162. if (nil == self.pdfConverter && nil != password) {
  163. self.pdfConverter = CPDFConverterHtml.init(url: url, password: password as? String)
  164. }
  165. self.pdfConverter?.delegate = self
  166. self.options = CPDFConvertHtmlOptions()
  167. if ((tParams.value(forKey: "paneOptions") as? NSNumber) != nil) {
  168. (self.options as! CPDFConvertHtmlOptions).paneOptions = CPDFConvertHtmlPageAndNavigationPaneOptions(rawValue: (tParams.value(forKey: "paneOptions") as! NSNumber).intValue)!
  169. }
  170. self.pdfConverter?.convert(toFilePath: cachePath,
  171. pageIndexs: self.pages, options: self.options)
  172. }
  173. }else if !useOldLib && NSArray(array: ["rtf", "RTF"]).contains(self.pathExtension) {
  174. autoreleasepool {
  175. self.pdfConverter = CPDFConverterRtf.init(url: url, password: nil)
  176. if (nil == self.pdfConverter && nil != password) {
  177. self.pdfConverter = CPDFConverterRtf.init(url: url, password: password as? String)
  178. }
  179. self.pdfConverter?.delegate = self
  180. self.options = CPDFConvertRtfOptions()
  181. self.pdfConverter?.convert(toFilePath: self.desPath,
  182. pageIndexs: self.pages, options: self.options)
  183. }
  184. }else if !useOldLib && NSArray(array: ["txt", "TXT"]).contains(self.pathExtension) {
  185. autoreleasepool {
  186. self.pdfConverter = CPDFConverterTxt.init(url: url, password: nil)
  187. if (nil == self.pdfConverter && nil != password) {
  188. self.pdfConverter = CPDFConverterTxt.init(url: url, password: password as? String)
  189. }
  190. self.pdfConverter?.delegate = self
  191. self.options = CPDFConvertTxtOptions()
  192. self.pdfConverter?.convert(toFilePath: self.desPath,
  193. pageIndexs: self.pages, options: self.options)
  194. }
  195. }else {
  196. autoreleasepool {
  197. if self.fpConverter == nil {
  198. self.fpConverter = CPDFConverterFP.init()
  199. self.fpConverter?.setDelegate(self)
  200. }else {
  201. self.fpConverter?.stopConvertsionIfNeed()
  202. }
  203. var needMerge = NSArray(array: ["csv", "CSV"]).contains(self.pathExtension)
  204. let dpi = tParams.value(forKey: "KMPDFConvertOptionsKeyImageDPI")
  205. if (needMerge && tParams.value(forKey: "CPDFConvertOptionsKeyAllInOneSheet") != nil) {
  206. needMerge = (tParams.value(forKey: "CPDFConvertOptionsKeyAllInOneSheet") as! NSNumber).boolValue
  207. }
  208. self.fpConverter?.convertPDF(atPath: self.srcPath,
  209. pdfPassword: password as? String,
  210. pdfPageIndexs: self.pages,
  211. destDocType: self.pathExtension,
  212. destDocPath: self.desPath,
  213. moreOptions: [
  214. "KMPDFConvertOptionsKeyImageDPI" : (dpi as? String) ?? "72",
  215. "CPDFConvertOptionsKeyAllInOneSheet":NSNumber(booleanLiteral: needMerge)
  216. ])
  217. }
  218. }
  219. }
  220. }
  221. func converter(_ inSrcPath: String, inDesPath: String) -> Int {
  222. return converter(inSrcPath, inDesPath: inDesPath, params: nil)
  223. }
  224. func converter(_ inSrcPath: String, inDesPath: String, params:NSDictionary?) -> Int {
  225. if !FileManager.default.fileExists(atPath: inSrcPath) {
  226. return -1
  227. }
  228. accessSemaphore?.wait()
  229. converter(inSrcPath, inDesPath: inDesPath, params: params) { status in
  230. self.semaphore?.signal()
  231. };
  232. semaphore?.wait()
  233. accessSemaphore?.signal()
  234. return didSuccess
  235. }
  236. /// CPDFConverterDelegate
  237. func converter(_ converter: CPDFConverter!, didStartConvert error: Error!) {
  238. didSuccess = 0;
  239. }
  240. func converter(_ converter: CPDFConverter!, didEndConvert error: Error!) {
  241. didSuccess = nil == error ? 1 : 0
  242. Thread.sleep(forTimeInterval: 0.1)
  243. autoreleasepool {
  244. if NSArray(array: ["jpg", "JPG", "png", "PNG", "HTML", "html", "csv", "CSV"]).contains(self.pathExtension) {
  245. let cachePath = NSString(string: self.desPath).deletingPathExtension+".zip"
  246. let zip = ZipArchive.init()
  247. zip.unzipOpenFile(cachePath)
  248. zip.unzipFile(to: self.desPath, overWrite: true)
  249. try? FileManager.default.removeItem(atPath: cachePath)
  250. }
  251. if self.pdfConverter?.isConverting == true {
  252. self.pdfConverter?.cancel()
  253. }
  254. self.pdfConverter?.delegate = nil
  255. self.pdfConverter = nil
  256. self.complention(didSuccess)
  257. }
  258. }
  259. func converter(_ converter: CPDFConverter!, pageIndex index: UInt, pageCount count: UInt) {
  260. }
  261. /// CPDFConverterFPDelegate
  262. func fppdfConverter(_ converter: Any!, didEndConversion error: Error!) {
  263. autoreleasepool {
  264. didSuccess = nil == error ? 1 : 0
  265. self.fpConverter?.stopConvertsionIfNeed()
  266. Thread.sleep(forTimeInterval: 0.3)
  267. self.complention(didSuccess)
  268. }
  269. }
  270. }