FileConverter.swift 15 KB

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