KMExtractImageWindowController.swift 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  1. //
  2. // KMExtractImageWindowController.swift
  3. // PDF Master
  4. //
  5. // Created by liujiajie on 2023/11/17.
  6. //
  7. import Cocoa
  8. class KMExtractImageWindowController: NSWindowController,PDFConvertObjectDelegate,NSTextFieldDelegate{
  9. var docPath: String = ""
  10. var password: String = ""
  11. var currentPage: Int = 0
  12. var maskView: KMBookletMaskView?
  13. @IBOutlet var rangeTipLabel: NSTextField!
  14. @IBOutlet var rangeTextField: NSTextField!
  15. @IBOutlet var allPageButton: NSButton!
  16. @IBOutlet var currentPageButton: NSButton!
  17. @IBOutlet var singlePageButton: NSButton!
  18. @IBOutlet var doublePageButton: NSButton!
  19. @IBOutlet var customPageButton: NSButton!
  20. @IBOutlet var extractImageButton: NSButton!
  21. @IBOutlet var cancelButton: NSButton!
  22. @IBOutlet var customTextField: NSTextField!
  23. @IBOutlet var totalImagesTextField: NSTextField!
  24. lazy var pdfDocument: CPDFDocument? = {
  25. var pdfDoc = CPDFDocument(url: URL(fileURLWithPath: self.docPath))
  26. if (self.password.count > 0){
  27. pdfDoc?.unlock(withPassword: self.password)
  28. }
  29. return pdfDoc
  30. }()
  31. var selectPagesIndex: Int = 0
  32. // var pdfConverter: PDFConvertObject?
  33. lazy var pdfConverter: PDFConvertObject? = {
  34. let conerter = PDF_Master.PDFConvertObject()
  35. return conerter
  36. }()
  37. @IBOutlet var currentPageTextField: NSTextField!
  38. @IBOutlet var pageCountTextField: NSTextField!
  39. @IBOutlet var pdfViewBG: NSView!
  40. var preViewPDFView: CPDFView!
  41. deinit {
  42. NotificationCenter.default.removeObserver(self)
  43. }
  44. override func windowDidLoad() {
  45. super.windowDidLoad()
  46. let preView: CPDFView = CPDFView(frame: self.pdfViewBG.bounds)
  47. self.pdfViewBG.addSubview(preView)
  48. self.preViewPDFView = preView
  49. configUI()
  50. }
  51. func configUI() {
  52. if !self.docPath.isEmpty && self.docPath.count > 0 {
  53. let url = URL(fileURLWithPath: docPath)
  54. let document = CPDFDocument(url: url)
  55. if self.password.count > 0 {
  56. document?.unlock(withPassword: password)
  57. }
  58. self.preViewPDFView.document = document
  59. self.preViewPDFView.autoScales = true
  60. self.preViewPDFView.layoutDocumentView()
  61. self.preViewPDFView.go(toPageIndex: self.currentPage, animated: true)
  62. }
  63. self.allPageButton.title = NSLocalizedString("All Pages", comment: "")
  64. self.singlePageButton.title = NSLocalizedString("Odd Pages Only", comment: "")
  65. self.doublePageButton.title = NSLocalizedString("Even Pages Only", comment: "")
  66. self.currentPageButton.title = NSLocalizedString("Current Page", comment: "")
  67. self.extractImageButton.title = NSLocalizedString("Extract", comment: "")
  68. self.cancelButton.title = NSLocalizedString("Cancel", comment: "")
  69. self.rangeTextField.placeholderString = NSLocalizedString("e.g. 1,3-5,10", comment: "")
  70. self.rangeTipLabel.stringValue = NSLocalizedString("Page Range", comment: "")
  71. self.currentPageTextField.stringValue = "\(self.currentPage + 1)"
  72. self.pageCountTextField.stringValue = "/ \(self.pdfDocument?.pageCount ?? 0)"
  73. self.customTextField.stringValue = self.pageCountTextField.stringValue
  74. self.selectPagesIndex = 0
  75. self.rangeTextField.isEnabled = false
  76. self.customTextField.isEnabled = false
  77. self.allPageButton.state = NSControl.StateValue.on
  78. if self.pdfDocument?.pageCount ?? 0 < 2 {
  79. self.doublePageButton.isEnabled = false
  80. } else {
  81. self.doublePageButton.isEnabled = true
  82. }
  83. NotificationCenter.default.addObserver(self, selector: #selector(pageChangeNotification(notification:)), name: NSNotification.Name.PDFViewPageChanged, object: self.preViewPDFView)
  84. }
  85. func selectCurrentPageBtn() {
  86. self.customPageButton_Action(self.currentPageButton)
  87. }
  88. @IBAction func customPageButton_Action(_ sender: NSButton) {
  89. self.allPageButton.state = NSControl.StateValue.off
  90. self.currentPageButton.state = NSControl.StateValue.off
  91. self.singlePageButton.state = NSControl.StateValue.off
  92. self.doublePageButton.state = NSControl.StateValue.off
  93. self.customPageButton.state = NSControl.StateValue.off
  94. sender.state = NSControl.StateValue.on
  95. self.rangeTextField.isEnabled = false
  96. self.customTextField.textColor = NSColor.disabledControlTextColor
  97. self.selectPagesIndex = sender.tag
  98. if sender.tag == 3 {
  99. self.rangeTextField.isEnabled = true
  100. self.customTextField.textColor = NSColor.labelColor
  101. self.window?.makeFirstResponder(self.rangeTextField)
  102. if self.rangeTextField.stringValue.isEmpty {
  103. return
  104. }
  105. }
  106. }
  107. @IBAction func extractImageButton_Action(_ sender: Any) {
  108. startExtracting()
  109. }
  110. @IBAction func cancleButton_Action(_ sender: Any) {
  111. self.window?.sheetParent?.endSheet(self.window!)
  112. }
  113. @IBAction func nextPage_Action(_ sender: Any) {
  114. if self.preViewPDFView.canGoToNextPage() {
  115. self.preViewPDFView.goToNextPage(sender)
  116. }
  117. let index = self.preViewPDFView.document.index(for: self.preViewPDFView.currentPage())
  118. self.currentPageTextField.stringValue = "\(index + 1)"
  119. }
  120. @IBAction func previousPage_Action(_ sender: Any) {
  121. if self.preViewPDFView.canGoToPreviousPage() {
  122. self.preViewPDFView.goToPreviousPage(sender)
  123. }
  124. let index = self.preViewPDFView.document.index(for: self.preViewPDFView.currentPage())
  125. self.currentPageTextField.stringValue = "\(index + 1)"
  126. }
  127. override func close() {
  128. if ((self.window?.isSheet) != nil) {
  129. self.window?.sheetParent?.endSheet(self.window!)
  130. } else {
  131. super.close()
  132. }
  133. }
  134. func startExtracting() {
  135. let indeSet = self.selectIndexSet()
  136. if indeSet.count == 0 { return }
  137. let lastPathName = self.pdfDocument?.documentURL.deletingPathExtension().lastPathComponent ?? ""
  138. let tFileName = (String(format: "%@_Extract Images", lastPathName))
  139. let outputSavePanel = NSSavePanel()
  140. outputSavePanel.title = NSLocalizedString("Save as PDF", comment: "")
  141. outputSavePanel.allowsOtherFileTypes = true
  142. outputSavePanel.isExtensionHidden = true
  143. outputSavePanel.canCreateDirectories = true
  144. outputSavePanel.nameFieldStringValue = tFileName
  145. outputSavePanel.beginSheetModal(for: self.window!) {(result) in
  146. if result == NSApplication.ModalResponse.OK {
  147. self.showWaitting()
  148. DispatchQueue.main.async {
  149. let tDestFile = outputSavePanel.url?.path ?? ""
  150. let uniquePath = KMExtractImageWindowController.createDestFolder(path: tDestFile, isUnique: false)
  151. self.pdfConverter?.extractResourcesFromPDF(at: self.docPath, pdfPassword: self.password, selectIndexSet: indeSet as IndexSet, destDocPath: uniquePath, moreOptions: nil)
  152. self.extractOK(tDestFile)
  153. }
  154. }
  155. }
  156. }
  157. func extractOK(_ folder: String) {
  158. self.hideWaitting()
  159. self.close()
  160. if FileManager.default.fileExists(atPath: folder) {
  161. let workspace = NSWorkspace.shared
  162. let url = URL(fileURLWithPath: folder)
  163. workspace.activateFileViewerSelecting([url])
  164. }
  165. }
  166. func selectIndexSet() -> NSMutableIndexSet {
  167. let pageCount = self.pdfDocument?.pageCount
  168. let indeSet = NSMutableIndexSet()
  169. if self.selectPagesIndex == 0 {
  170. for i in 0..<(pageCount ?? 0) {
  171. indeSet.add(IndexSet(integer: IndexSet.Element(i)))
  172. }
  173. } else if self.selectPagesIndex == 1 {
  174. for i in 0..<(pageCount ?? 0) {
  175. if i % 2 == 0 {
  176. indeSet.add(IndexSet(integer: IndexSet.Element(i)))
  177. }
  178. }
  179. } else if self.selectPagesIndex == 2 {
  180. for i in 0..<(pageCount ?? 0) {
  181. if i % 2 != 0 {
  182. indeSet.add(IndexSet(integer: IndexSet.Element(i)))
  183. }
  184. }
  185. } else if self.selectPagesIndex == 4 {
  186. if let index = self.preViewPDFView.document?.index(for: self.preViewPDFView.currentPage()!) {
  187. indeSet.add(IndexSet(integer: IndexSet.Element(index)))
  188. }
  189. } else {
  190. let fileAttribute = KMFileAttribute()
  191. fileAttribute.filePath = self.preViewPDFView.document?.documentURL?.path ?? ""
  192. fileAttribute.bAllPage = false
  193. fileAttribute.pagesString = self.rangeTextField.stringValue
  194. if !fileAttribute.fetchSelectPages().isEmpty {
  195. let alert = NSAlert()
  196. alert.alertStyle = .critical
  197. alert.messageText = "\(fileAttribute.filePath.lastPathComponent) \(NSLocalizedString("Invalid page range or the page number is out of range. Please try again.", comment: ""))"
  198. alert.runModal()
  199. return indeSet
  200. }
  201. for num in fileAttribute.fetchSelectPages() {
  202. indeSet.add(num.intValue-1)
  203. }
  204. }
  205. return indeSet
  206. }
  207. class func createDestFolder(path: String, isUnique: Bool) -> String {
  208. var ret = true
  209. var tUniqueName: String? = nil
  210. let tFileManager = FileManager.default
  211. if isUnique {
  212. tUniqueName = getUniqueFilePath(filePath: path)
  213. } else {
  214. tUniqueName = path
  215. }
  216. if !tFileManager.fileExists(atPath: tUniqueName!) {
  217. do {
  218. try tFileManager.createDirectory(atPath: tUniqueName!, withIntermediateDirectories: true, attributes: nil)
  219. } catch {
  220. ret = false
  221. }
  222. }
  223. return tUniqueName!
  224. }
  225. class func getUniqueFilePath(filePath: String) -> String {
  226. var i = 0
  227. var isDirectory = ObjCBool(false)
  228. var uniqueFilePath = filePath
  229. let filemanager = FileManager.default
  230. filemanager.fileExists(atPath: uniqueFilePath, isDirectory: &isDirectory)
  231. if isDirectory.boolValue {
  232. while filemanager.fileExists(atPath: uniqueFilePath) {
  233. i += 1
  234. uniqueFilePath = "\(filePath)(\(i))"
  235. }
  236. } else {
  237. while filemanager.fileExists(atPath: uniqueFilePath) {
  238. i += 1
  239. let path = "\(filePath.deletingPathExtension)(\(i))"
  240. uniqueFilePath = path.stringByAppendingPathExtension(filePath.customPathExtension)
  241. }
  242. }
  243. return uniqueFilePath
  244. }
  245. @objc func pageChangeNotification(notification: Notification) {
  246. self.currentPageTextField.stringValue = self.preViewPDFView.currentPage().label ?? ""
  247. }
  248. func controlTextDidEndEditing(_ obj: Notification) {
  249. if obj.object as? NSTextField == self.currentPageTextField {
  250. if let intValue = Int(self.currentPageTextField.stringValue), intValue > (self.preViewPDFView.document?.pageCount ?? 0) {
  251. let alert = NSAlert()
  252. alert.alertStyle = .critical
  253. alert.messageText = String(format: "%@%@", self.preViewPDFView.document.documentURL.lastPathComponent.lastPathComponent,KMLocalizedString("Invalid page range or the page number is out of range. Please try again.", nil))
  254. alert.beginSheetModal(for: NSApp.mainWindow!, completionHandler: nil)
  255. return
  256. }
  257. self.preViewPDFView.go(to: self.preViewPDFView.document?.page(at: UInt((Int(self.currentPageTextField.stringValue) ?? 0) - 1)))
  258. } else if obj.object as? NSTextField == self.rangeTextField {
  259. if !checkPageRangeValidate(self.rangeTextField.stringValue) {
  260. let alert = NSAlert()
  261. alert.alertStyle = .critical
  262. alert.messageText = String(format: "%@%@", self.preViewPDFView.document.documentURL.lastPathComponent.lastPathComponent,KMLocalizedString("Invalid page range or the page number is out of range. Please try again.", nil))
  263. alert.beginSheetModal(for: NSApp.mainWindow!, completionHandler: nil)
  264. return
  265. }
  266. }
  267. }
  268. func checkPageRangeValidate(_ pageRangeString: String) -> Bool {
  269. let fileAttribute = KMFileAttribute()
  270. fileAttribute.filePath = self.preViewPDFView.document?.documentURL?.path ?? ""
  271. fileAttribute.bAllPage = false
  272. fileAttribute.pagesString = self.rangeTextField.stringValue
  273. if fileAttribute.fetchSelectPages().isEmpty || fileAttribute.fetchSelectPages().count < 1{
  274. return false
  275. }
  276. return true
  277. }
  278. override func mouseDown(with event: NSEvent) {
  279. super.mouseDown(with: event)
  280. self.window?.makeFirstResponder(nil)
  281. }
  282. @objc func pageChangeNotification(_ notification: Notification) {
  283. self.currentPageTextField.stringValue = self.preViewPDFView.currentPage().label ?? ""
  284. }
  285. func PDFConvertObject(_ converter: PDFConvertObject, didEndConversion error: Error?) {
  286. self.hideWaitting()
  287. self.window?.sheetParent?.endSheet(self.window!)
  288. }
  289. func showWaitting() {
  290. if self.maskView == nil {
  291. self.maskView = KMBookletMaskView(frame: CGRect(x: 0, y: 0, width: self.window?.frame.size.width ?? 0, height: self.window?.frame.size.height ?? 0))
  292. }
  293. self.window?.contentView?.addSubview(self.maskView!)
  294. }
  295. func hideWaitting() {
  296. self.maskView?.removeFromSuperview()
  297. }
  298. func beginSheetModal(for window: NSWindow, completionHandler handler: ((NSInteger) -> Void)?) {
  299. self.window?.beginSheet(window, completionHandler: { returnCode in
  300. NSApp.endSheet(self.window!, returnCode: NSApplication.ModalResponse.abort.rawValue)
  301. if let handler = handler {
  302. handler(returnCode.rawValue)
  303. }
  304. })
  305. }
  306. }