KMPDFConvert.swift 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  1. //
  2. // KMPDFConvert.swift
  3. // PDF Master
  4. //
  5. // Created by tangchao on 2022/12/7.
  6. //
  7. import Cocoa
  8. import PDFKit
  9. import ComPDFKit_Conversion
  10. let KMPDFConvertOptionsKeyImageDPI = "KMPDFConvertOptionsKeyImageDPI"
  11. let KMPDFConvertOptionsKeyImageWithAnnotation = "KMPDFConvertOptionsKeyImageWithAnnotation"
  12. enum KMPDFConvertType: Int {
  13. case word = 0
  14. case excel = 1
  15. case ppt = 2
  16. case rtf = 3
  17. case csv = 4
  18. case html = 5
  19. case text = 6
  20. case jpeg = 7
  21. case jpg = 8
  22. case png = 9
  23. case gif = 10
  24. case tiff = 11
  25. case tga = 12
  26. case bmp = 13
  27. case jp2 = 14
  28. }
  29. typealias KMPDFConvertCallback = (_ finished: Bool, _ error: Error?) -> ()
  30. typealias KMPDFConvertProgress = (Int) -> ()
  31. class KMPDFConvert: Operation {
  32. var type: Int = 0
  33. var filePath: String = ""
  34. var password: String = ""
  35. var outputFileName: String = ""
  36. var outputFolderPath: String = ""
  37. var pages: [Int]!
  38. var convertType: KMPDFConvertType = .word
  39. var options: [String:Any]!
  40. var outputFilePath: String = ""
  41. var isSuccessful: Bool = false
  42. var isAllInOneSheet: Bool = false
  43. var isExtractTable: Bool = false
  44. var isExtractText: Bool = false
  45. /**
  46. 0 支持一个表格提取到单独的工作表
  47. 1 支持按页面提取表格到单独的工作表
  48. 2 支持将所有表格提取到一个工作表
  49. */
  50. var extractTableIndex: Int = 0
  51. var errorInfo: Error!
  52. private var pathExtension: String = ""
  53. private var fpPDFConverter: CPDFConverterFP!
  54. private var converter: CPDFConverter!
  55. private var isCompletion: Bool = false
  56. var callback: KMPDFConvertCallback!
  57. var progress: KMPDFConvertProgress?
  58. public class func pathExtension(_ type: KMPDFConvertType) -> String {
  59. return self.pathExtension(type, nil)
  60. }
  61. public class func pathExtension(_ type: KMPDFConvertType, _ isExtractTable: Bool?) -> String {
  62. if type == .word {
  63. return "docx"
  64. } else if type == .excel {
  65. return "xlsx"
  66. } else if type == .ppt {
  67. return "pptx"
  68. } else if type == .rtf {
  69. return "rtf"
  70. } else if type == .csv {
  71. if isExtractTable != nil && isExtractTable! {
  72. return "zip"
  73. }
  74. return "csv"
  75. } else if type == .html {
  76. return "html"
  77. } else if type == .text {
  78. return "txt"
  79. } else if type == .jpeg {
  80. return "jpeg"
  81. } else if type == .jpg {
  82. return "jpg"
  83. } else if type == .png {
  84. return "png"
  85. } else if type == .gif {
  86. return "gif"
  87. } else if type == .tga {
  88. return "tga"
  89. } else if type == .bmp {
  90. return "bmp"
  91. } else if type == .jp2 {
  92. return "jp2"
  93. } else if type == .tiff {
  94. return "tiff"
  95. }
  96. return ""
  97. }
  98. override func start() {
  99. if isCancelled {
  100. return
  101. }
  102. var pathExtension = KMPDFConvert.pathExtension(self.convertType, self.isExtractTable)
  103. var fileName = outputFileName
  104. var path = outputFolderPath
  105. if convertType == .jpeg || convertType == .jpg || convertType == .png || convertType == .gif || convertType == .tga || convertType == .bmp || convertType == .jp2 || convertType == .tiff {
  106. path.append("/")
  107. path.append(fileName)
  108. // let folderPath = getUniqueFilePath(filePath: path)
  109. try?FileManager.default.createDirectory(atPath: path, withIntermediateDirectories: false)
  110. outputFilePath = path
  111. } else {
  112. if !pathExtension.isEmpty {
  113. fileName.append(".")
  114. fileName.append(pathExtension)
  115. path.append("/")
  116. path.append(fileName)
  117. // let folderPath = getUniqueFilePath(filePath: path)
  118. outputFilePath = path
  119. } else {
  120. outputFolderPath.append("/")
  121. outputFolderPath.append(outputFileName)
  122. outputFilePath = outputFolderPath
  123. }
  124. }
  125. self.pathExtension = pathExtension
  126. convertWithFPPDFConverter()
  127. }
  128. func getUniqueFilePath(filePath: String) -> String {
  129. var i: Int = 0
  130. var isDirectory: ObjCBool = false
  131. var uniqueFilePath = filePath
  132. let fileManager = FileManager.default
  133. fileManager.fileExists(atPath: uniqueFilePath, isDirectory: &isDirectory)
  134. if isDirectory.boolValue {
  135. var path: String = ""
  136. while fileManager.fileExists(atPath: uniqueFilePath) {
  137. i += 1
  138. path = filePath
  139. path.append("(\(i))")
  140. uniqueFilePath = path
  141. }
  142. } else {
  143. let fileURL = URL(fileURLWithPath: filePath)
  144. var path: String = ""
  145. while fileManager.fileExists(atPath: uniqueFilePath) {
  146. i += 1
  147. path = fileURL.deletingPathExtension().path
  148. path.append("(\(i))")
  149. path.append(".")
  150. path.append(fileURL.pathExtension)
  151. uniqueFilePath = path
  152. }
  153. }
  154. return uniqueFilePath
  155. }
  156. func convertWithFPPDFConverter() {
  157. if pathExtension.isEmpty {
  158. convertSuccessful(isSuccessful: false, errorInfo: nil)
  159. return
  160. }
  161. if convertType == .word && isAllInOneSheet {
  162. converter = CPDFConverterWord(url: URL(fileURLWithPath: filePath), password: self.password)
  163. converter.delegate = self
  164. converter.convert(toFilePath: outputFilePath, pageIndexs: pages, options: nil)
  165. return
  166. }
  167. if convertType == .excel {
  168. converter = CPDFConverterExcel(url: URL(fileURLWithPath: filePath), password: self.password)
  169. converter.delegate = self
  170. let options = CPDFConvertExcelOptions()
  171. if (isExtractText) {
  172. options.contentOptions = .onlyText
  173. } else if (isExtractTable) {
  174. options.contentOptions = .onlyTable
  175. if (extractTableIndex == 0) {
  176. options.worksheetOptions = .forEachTable
  177. } else if (extractTableIndex == 1) {
  178. options.worksheetOptions = .forEachPage
  179. } else if (extractTableIndex == 2) {
  180. options.worksheetOptions = .forTheDocument
  181. }
  182. } else {
  183. options.contentOptions = .allContent
  184. if (isAllInOneSheet) {
  185. options.worksheetOptions = .forTheDocument
  186. } else {
  187. options.worksheetOptions = .forEachPage
  188. }
  189. }
  190. converter.convert(toFilePath: outputFilePath, pageIndexs: pages, options: options)
  191. return
  192. }
  193. if (convertType == .ppt) {
  194. converter = CPDFConverterPPT(url: URL(fileURLWithPath: filePath), password: self.password)
  195. converter.delegate = self
  196. converter.convert(toFilePath: outputFilePath, pageIndexs: pages, options: nil)
  197. return
  198. }
  199. if (convertType == .text) {
  200. converter = CPDFConverterTxt(url: URL(fileURLWithPath: filePath), password: self.password)
  201. converter.delegate = self
  202. converter.convert(toFilePath: outputFilePath, pageIndexs: pages, options: nil)
  203. return
  204. }
  205. if convertType == .csv && isExtractTable {
  206. converter = CPDFConverterCsv(url: URL(fileURLWithPath: filePath), password: self.password)
  207. converter.delegate = self
  208. converter.convert(toFilePath: outputFilePath, pageIndexs: pages, options: nil)
  209. return
  210. }
  211. // if (convertType == .jpeg || convertType == .png) {
  212. // converter = CPDFConverterImg(url: URL(fileURLWithPath: filePath), password: nil)
  213. // converter.delegate = self
  214. // let options = CPDFConvertImgOptions()
  215. // if (convertType == .jpeg) {
  216. // options.type = .JPEG
  217. // } else if (convertType == .png) {
  218. // options.type = .PNG
  219. // }
  220. // converter.convert(toFilePath: outputFilePath, pageIndexs: pages, options: options)
  221. // return
  222. // }
  223. fpPDFConverter = CPDFConverterFP()
  224. fpPDFConverter.setDelegate(self)
  225. var dpi: Int = 0
  226. if self.options != nil {
  227. dpi = self.options[KMPDFConvertOptionsKeyImageDPI] as! Int
  228. }
  229. let options: [String:Any] = [CPDFConvertOptionsKey.imageDPI.rawValue:dpi,CPDFConvertOptionsKey.allInOneSheet.rawValue:isAllInOneSheet]
  230. fpPDFConverter.convertPDF(atPath: filePath, pdfPassword: self.password, pdfPageIndexs: pages, destDocType: pathExtension, destDocPath: outputFilePath, moreOptions: options)
  231. }
  232. func convertSuccessful(isSuccessful: Bool, errorInfo: Error!) {
  233. self.isSuccessful = isSuccessful
  234. self.errorInfo = errorInfo
  235. DispatchQueue.main.async { [self] in
  236. guard let callbackBlock = callback else {
  237. return
  238. }
  239. callbackBlock(isSuccessful, errorInfo)
  240. }
  241. willChangeValue(forKey: "isFinished")
  242. isCompletion = true
  243. didChangeValue(forKey: "isFinished")
  244. }
  245. override var isFinished: Bool {
  246. return self.isCompletion
  247. }
  248. }
  249. extension KMPDFConvert: CPDFConverterDelegate {
  250. func converter(_ converter: CPDFConverter!, didStartConvert error: Error!) {
  251. }
  252. func converter(_ converter: CPDFConverter!, didEndConvert error: Error!) {
  253. if (error != nil) {
  254. convertSuccessful(isSuccessful: false, errorInfo: error)
  255. } else {
  256. convertSuccessful(isSuccessful: true, errorInfo: error)
  257. }
  258. }
  259. func converter(_ converter: CPDFConverter!, pageIndex index: UInt, pageCount count: UInt) {
  260. guard let callback = progress else {
  261. return
  262. }
  263. callback(Int(index))
  264. }
  265. }
  266. extension KMPDFConvert: CPDFConverterFPDelegate {
  267. func fppdfConverter(_ converter: Any!, didEndConversion error: Error!) {
  268. if (error != nil) {
  269. convertSuccessful(isSuccessful: false, errorInfo: error)
  270. } else {
  271. convertSuccessful(isSuccessful: true, errorInfo: error)
  272. }
  273. }
  274. func fppdfConverter(_ converter: Any!, convertPDFPageIndex pdfPageIndexA: UInt, writeWordPageIndex wordPageIndexA: UInt, finshedWordPageCount wordPageCountA: UInt) {
  275. guard let callback = progress else {
  276. return
  277. }
  278. callback(Int(wordPageIndexA))
  279. }
  280. }