KMAIOpenPDFFilesVC.swift 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398
  1. //
  2. // KMAIOpenPDFFilesVC.swift
  3. // PDF Master
  4. //
  5. // Created by wanjun on 2023/5/22.
  6. //
  7. import Cocoa
  8. class KMAIOpenPDFFilesVC: NSViewController {
  9. @IBOutlet weak var openPDFFilesLabel: NSTextField!
  10. @IBOutlet weak var openPDFFilesImageView: NSImageView!
  11. @IBOutlet weak var selectYourFilesBox: KMBox!
  12. @IBOutlet weak var selectYourFilesLabel: NSTextField!
  13. @IBOutlet weak var selectYourFilesImageView: NSImageView!
  14. @IBOutlet weak var orDropFilesHereToOpenLabel: NSTextField!
  15. @IBOutlet weak var creatPDFLabel: NSTextField!
  16. @IBOutlet weak var newFromFilesLabel: NSTextField!
  17. @IBOutlet weak var newFromFilesImageView: NSImageView!
  18. @IBOutlet weak var newBlankPageLabel: NSTextField!
  19. @IBOutlet weak var newBlankPageImageView: NSImageView!
  20. @IBOutlet weak var importFromScannerLabel: NSTextField!
  21. @IBOutlet weak var importFromScannerImageView: NSImageView!
  22. var deviceBrowserWC: KMDeviceBrowserWindowController?
  23. override func viewDidLoad() {
  24. super.viewDidLoad()
  25. // Do view setup here.
  26. self.initLocalization()
  27. self.initializeUI()
  28. }
  29. // MARK: initialize
  30. func initializeUI() -> Void {
  31. self.openPDFFilesLabel.textColor = NSColor(hex: "#252629")
  32. self.openPDFFilesLabel.font = NSFont.SFProTextSemibold(20.0)
  33. self.openPDFFilesImageView.image = NSImage(named: "icon_empty_addFiles")
  34. self.selectYourFilesBox.cornerRadius = 4.0
  35. self.selectYourFilesBox.fillColor = NSColor(hex: "#1770F4")
  36. self.selectYourFilesLabel.textColor = NSColor(hex: "#FFFFFF")
  37. self.selectYourFilesLabel.font = NSFont.SFProTextRegular(16.0)
  38. self.selectYourFilesImageView.image = NSImage(named: "icon_SelectYourFiles")
  39. self.orDropFilesHereToOpenLabel.textColor = NSColor(hex: "#616469")
  40. self.orDropFilesHereToOpenLabel.font = NSFont.SFProTextRegular(14.0)
  41. self.creatPDFLabel.textColor = NSColor(hex: "#252629")
  42. self.creatPDFLabel.font = NSFont.SFProTextSemibold(20.0)
  43. self.newFromFilesLabel.textColor = NSColor(hex: "#252629")
  44. self.newFromFilesLabel.font = NSFont.SFProTextRegular(16.0)
  45. self.newFromFilesImageView.image = NSImage(named: "icon_empty_NewFromFiles")
  46. self.newBlankPageLabel.textColor = NSColor(hex: "#252629")
  47. self.newBlankPageLabel.font = NSFont.SFProTextRegular(16.0)
  48. self.newBlankPageImageView.image = NSImage(named: "icon_empty_NewBlackPage")
  49. self.importFromScannerLabel.textColor = NSColor(hex: "#252629")
  50. self.importFromScannerLabel.font = NSFont.SFProTextRegular(16.0)
  51. self.importFromScannerImageView.image = NSImage(named: "icon_empty_ImportFromScanner")
  52. self.selectYourFilesBox.moveCallback = { [unowned self](mouseEntered: Bool, mouseBox: KMBox) -> Void in
  53. if mouseEntered {
  54. self.selectYourFilesBox.fillColor = NSColor(hex: "#3F8FF6")
  55. } else {
  56. self.selectYourFilesBox.fillColor = NSColor(hex: "#1770F4")
  57. }
  58. }
  59. self.selectYourFilesBox.downCallback = { [unowned self](downEntered: Bool, mouseBox: KMBox, event) -> Void in
  60. if downEntered {
  61. self.openPDFButtonAction()
  62. }
  63. }
  64. }
  65. func initLocalization() -> Void {
  66. self.openPDFFilesLabel.stringValue = NSLocalizedString("Open PDF Files", comment: "")
  67. self.selectYourFilesLabel.stringValue = NSLocalizedString("Select Your Files", comment: "")
  68. self.orDropFilesHereToOpenLabel.stringValue = NSLocalizedString("or drop files here to open", comment: "")
  69. self.creatPDFLabel.stringValue = NSLocalizedString("Create PDF", comment: "")
  70. self.newFromFilesLabel.stringValue = NSLocalizedString("New From Files", comment: "")
  71. self.newBlankPageLabel.stringValue = NSLocalizedString("New Blank Page", comment: "")
  72. self.importFromScannerLabel.stringValue = NSLocalizedString("Import From Scanner", comment: "")
  73. }
  74. // MARK: Private Methods
  75. func openImageFile(url: URL) -> Void {
  76. let filePath = url.path
  77. let fileName: NSString = url.lastPathComponent as NSString
  78. let savePath = fetchUniquePath(fileName.kUrlToPDFFolderPath()).deletingLastPathComponent
  79. let imageName = NSString(string: NSString(string: filePath).lastPathComponent).deletingPathExtension
  80. let path = self.fetchDifferentFilePath(filePath: savePath + "/" + imageName + ".pdf")
  81. let document = CPDFDocument.init()
  82. var success = false
  83. //FIXME: 无法插入图片
  84. let image = NSImage(contentsOfFile: filePath)
  85. let insertPageSuccess = document?.insertPage(image!.size, withImage: filePath, at: document!.pageCount)
  86. if insertPageSuccess != nil {
  87. //信号量控制异步
  88. let semaphore = DispatchSemaphore(value: 0)
  89. DispatchQueue.global().async {
  90. success = ((document?.write(toFile: path)) != nil)
  91. semaphore.signal()
  92. }
  93. semaphore.wait()
  94. } else {
  95. }
  96. if success {
  97. if !path.isPDFValid() {
  98. let alert = NSAlert()
  99. alert.alertStyle = .critical
  100. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  101. alert.runModal()
  102. return
  103. }
  104. NSDocumentController.shared.openDocument(withContentsOf: URL(fileURLWithPath: path), display: true) { document, documentWasAlreadyOpen, error in
  105. if error != nil {
  106. NSApp.presentError(error!)
  107. return
  108. }
  109. }
  110. }
  111. }
  112. func openOfficeFile(url: URL) -> Void {
  113. let filePath = url.path
  114. let folderPath = "convertToPDF.pdf"
  115. let savePath = folderPath.kUrlToPDFFolderPath()
  116. if savePath == nil {
  117. return
  118. }
  119. KMConvertPDFManagerOC.convertFile(filePath, savePath: savePath!) { success, errorDic in
  120. if errorDic != nil || !success || !FileManager.default.fileExists(atPath: savePath!) {
  121. if FileManager.default.fileExists(atPath: savePath!) {
  122. try?FileManager.default.removeItem(atPath: savePath!)
  123. }
  124. let alert = NSAlert.init()
  125. alert.alertStyle = .critical
  126. var infoString = ""
  127. if errorDic != nil {
  128. for key in (errorDic! as Dictionary).keys {
  129. infoString = infoString.appendingFormat("%@\n", errorDic![key] as! CVarArg)
  130. }
  131. }
  132. alert.informativeText = NSLocalizedString("Please install Microsoft Office to create PDFs from Office files", comment: "")
  133. alert.messageText = NSLocalizedString("Failed to Create PDF", comment: "")
  134. alert.addButton(withTitle: NSLocalizedString("OK", comment: ""))
  135. alert.runModal()
  136. return
  137. }
  138. if !savePath!.isPDFValid() {
  139. let alert = NSAlert()
  140. alert.alertStyle = .critical
  141. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  142. alert.runModal()
  143. return
  144. }
  145. NSDocumentController.shared.openDocument(withContentsOf: URL(fileURLWithPath: savePath!), display: true) { document, documentWasAlreadyOpen, error in
  146. if error != nil {
  147. NSApp.presentError(error!)
  148. return
  149. }
  150. }
  151. }
  152. }
  153. func fetchUniquePath(_ originalPath: String) -> String {
  154. var path = originalPath
  155. let dManager = FileManager.default
  156. if !dManager.fileExists(atPath: path) {
  157. if path.extension.count < 1 {
  158. path = path.stringByAppendingPathExtension("pdf")
  159. }
  160. return path
  161. } else {
  162. let originalFullFileName = path.lastPathComponent
  163. let originalFileName = path.lastPathComponent.deletingPathExtension.lastPathComponent
  164. let originalExtension = path.extension
  165. let startIndex: Int = 0
  166. let endIndex: Int = startIndex + originalPath.count - originalFullFileName.count - 1
  167. let fileLocatePath = originalPath.substring(to: endIndex)
  168. var i = 1
  169. while (1 != 0) {
  170. var newName = String(format: "%@%ld", originalFileName, i)
  171. newName = String(format: "%@%@", newName, originalExtension)
  172. let newPath = fileLocatePath.stringByAppendingPathComponent(newName)
  173. if !dManager.fileExists(atPath: newPath) {
  174. return newPath
  175. } else {
  176. i+=1
  177. continue
  178. }
  179. }
  180. }
  181. }
  182. func fetchDifferentFilePath(filePath: String) -> String {
  183. var resultFilePath = filePath
  184. var index: Int = 0
  185. while (FileManager.default.fileExists(atPath: resultFilePath)) {
  186. index += 1
  187. let path = NSString(string: filePath).deletingPathExtension + "(" + String(index) + ")"
  188. resultFilePath = NSString(string: path).appendingPathExtension(NSString(string: filePath).pathExtension)!
  189. }
  190. return resultFilePath;
  191. }
  192. func openFile(withFilePath path: URL) -> Void {
  193. let type = path.pathExtension.lowercased()
  194. if (type == "pdf") {
  195. if !path.path.isPDFValid() {
  196. let alert = NSAlert()
  197. alert.alertStyle = .critical
  198. alert.messageText = NSLocalizedString("This file format is not supported, please drag in PDF, picture, Office format files", comment: "")
  199. alert.runModal()
  200. return
  201. }
  202. NSDocumentController.shared.openDocument(withContentsOf: path, display: true) { document, documentWasAlreadyOpen, error in
  203. if error != nil {
  204. NSApp.presentError(error!)
  205. return
  206. }
  207. }
  208. } else if (type == "jpg") ||
  209. (type == "cur") ||
  210. (type == "bmp") ||
  211. (type == "jpeg") ||
  212. (type == "gif") ||
  213. (type == "png") ||
  214. (type == "tiff") ||
  215. (type == "tif") ||
  216. (type == "ico") ||
  217. (type == "icns") ||
  218. (type == "tga") ||
  219. (type == "psd") ||
  220. (type == "eps") ||
  221. (type == "hdr") ||
  222. (type == "jp2") ||
  223. (type == "jpc") ||
  224. (type == "pict") ||
  225. (type == "sgi") ||
  226. (type == "heic") {
  227. openImageFile(url: path)
  228. } else if (type == "doc") ||
  229. (type == "docx") ||
  230. (type == "xls") ||
  231. (type == "xlsx") ||
  232. (type == "ppt") ||
  233. (type == "pptx") ||
  234. (type == "pptx") {
  235. let fileName: NSString = String(format: "%@.pdf", NSLocalizedString("Untitled", comment: "")) as NSString
  236. let savePath = fetchUniquePath(fileName.kUrlToPDFFolderPath())
  237. openOfficeFile(url: path)
  238. }
  239. }
  240. // MARK: Action
  241. @IBAction func createPDFAction(_ sender: NSButton) {
  242. let tag = sender.tag;
  243. if tag == 0 {
  244. // New From Files
  245. self.openSupportPDFButtonAction()
  246. } else if tag == 1 {
  247. // New Blank Page
  248. self.openBlankPage("")
  249. } else if tag == 2 {
  250. // Import From Scanner
  251. self.importFromScanner("")
  252. }
  253. }
  254. func openPDFButtonAction() {
  255. let openPanel = NSOpenPanel()
  256. openPanel.allowedFileTypes = ["pdf", "PDF"]
  257. openPanel.allowsMultipleSelection = true
  258. openPanel.beginSheetModal(for: self.view.window!) { result in
  259. if result == .OK {
  260. for url in openPanel.urls {
  261. if !url.path.isPDFValid() {
  262. let alert = NSAlert()
  263. alert.alertStyle = .critical
  264. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  265. alert.runModal()
  266. } else {
  267. NSDocumentController.shared.openDocument(withContentsOf: url, display: true) { document, documentWasAlreadyOpen, error in
  268. if error != nil {
  269. NSApp.presentError(error!)
  270. } else {
  271. }
  272. }
  273. }
  274. }
  275. }
  276. }
  277. }
  278. func openSupportPDFButtonAction() {
  279. let openPanel = NSOpenPanel()
  280. openPanel.allowedFileTypes = ["pdf", "PDF", "jpg", "cur", "bmp", "jpeg", "gif", "png", "tiff", "tif", "ico", "icns", "tga", "psd", "eps", "hdr", "jp2", "jpc", "pict", "sgi", "heic", "doc", "docx", "xls", "xlsx", "ppt", "pptx", "pptx"]
  281. openPanel.allowsMultipleSelection = true
  282. var window = self.view.window
  283. if (window == nil) {
  284. window = NSApp.mainWindow
  285. }
  286. openPanel.beginSheetModal(for: window!) { [self] result in
  287. if result == .OK {
  288. var imageUrl: [URL] = []
  289. for url in openPanel.urls {
  290. let type = url.pathExtension.lowercased()
  291. if (type == "pdf" || type == "PDF") {
  292. if !url.path.isPDFValid() {
  293. let alert = NSAlert()
  294. alert.alertStyle = .critical
  295. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  296. alert.runModal()
  297. } else {
  298. NSDocumentController.shared.openDocument(withContentsOf: url, display: true) { document, documentWasAlreadyOpen, error in
  299. if error != nil {
  300. NSApp.presentError(error!)
  301. return
  302. }
  303. }
  304. }
  305. } else if (type == "jpg") ||
  306. (type == "cur") ||
  307. (type == "bmp") ||
  308. (type == "jpeg") ||
  309. (type == "gif") ||
  310. (type == "png") ||
  311. (type == "tiff") ||
  312. (type == "tif") ||
  313. (type == "ico") ||
  314. (type == "icns") ||
  315. (type == "tga") ||
  316. (type == "psd") ||
  317. (type == "eps") ||
  318. (type == "hdr") ||
  319. (type == "jp2") ||
  320. (type == "jpc") ||
  321. (type == "pict") ||
  322. (type == "sgi") ||
  323. (type == "heic") {
  324. openImageFile(url: url)
  325. } else if (type == "doc") ||
  326. (type == "docx") ||
  327. (type == "xls") ||
  328. (type == "xlsx") ||
  329. (type == "ppt") ||
  330. (type == "pptx") ||
  331. (type == "pptx") {
  332. self.openOfficeFile(url: url)
  333. }
  334. }
  335. }
  336. }
  337. }
  338. @IBAction func openBlankPage(_ sender: Any) {
  339. let fileName: NSString = String(format: "%@.pdf", NSLocalizedString("Untitled", comment: "")) as NSString
  340. let savePath = fetchUniquePath(fileName.kUrlToPDFFolderPath())
  341. let pdfDocument = CPDFDocument()
  342. pdfDocument?.insertPage(CGSize(width: 595, height: 842), at: 0)
  343. pdfDocument?.write(to: URL(fileURLWithPath: savePath))
  344. NSDocumentController.shared.openDocument(withContentsOf: URL(fileURLWithPath: savePath), display: true) { document, documentWasAlreadyOpen, error in
  345. if error != nil {
  346. NSApp.presentError(error!)
  347. } else {
  348. if document is KMMainDocument {
  349. let newDocument = document
  350. (newDocument as! KMMainDocument).isNewCreated = true
  351. }
  352. }
  353. }
  354. }
  355. @IBAction func importFromScanner(_ sender: Any) {
  356. deviceBrowserWC = KMDeviceBrowserWindowController.init(windowNibName: "KMDeviceBrowserWindowController")
  357. deviceBrowserWC!.type = .scanner
  358. deviceBrowserWC!.importScannerFileCallback = { [unowned self](url: NSURL) -> Void in
  359. openFile(withFilePath: url as URL)
  360. }
  361. deviceBrowserWC!.showWindow(NSApp.mainWindow)
  362. }
  363. }