FileConverter.swift 15 KB

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