KMExtractImageWindowController.swift 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  1. //
  2. // KMExtractImageWindowController.swift
  3. // PDF Reader Pro
  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 = 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. self.preViewPDFView.setDisplay(.singlePage)
  84. self.preViewPDFView.layoutDocumentView()
  85. NotificationCenter.default.addObserver(self, selector: #selector(pageChangeNotification(notification:)), name: NSNotification.Name.PDFViewPageChanged, object: self.preViewPDFView)
  86. }
  87. func selectCurrentPageBtn() {
  88. self.customPageButton_Action(self.currentPageButton)
  89. }
  90. @IBAction func customPageButton_Action(_ sender: NSButton) {
  91. self.allPageButton.state = NSControl.StateValue.off
  92. self.currentPageButton.state = NSControl.StateValue.off
  93. self.singlePageButton.state = NSControl.StateValue.off
  94. self.doublePageButton.state = NSControl.StateValue.off
  95. self.customPageButton.state = NSControl.StateValue.off
  96. sender.state = NSControl.StateValue.on
  97. self.rangeTextField.isEnabled = false
  98. self.customTextField.textColor = NSColor.disabledControlTextColor
  99. self.selectPagesIndex = sender.tag
  100. if sender.tag == 3 {
  101. self.rangeTextField.isEnabled = true
  102. self.customTextField.textColor = NSColor.labelColor
  103. self.window?.makeFirstResponder(self.rangeTextField)
  104. if self.rangeTextField.stringValue.isEmpty {
  105. return
  106. }
  107. }
  108. }
  109. @IBAction func extractImageButton_Action(_ sender: Any) {
  110. startExtracting()
  111. }
  112. @IBAction func cancleButton_Action(_ sender: Any) {
  113. self.window?.sheetParent?.endSheet(self.window!)
  114. }
  115. @IBAction func nextPage_Action(_ sender: Any) {
  116. if self.preViewPDFView.canGoToNextPage() {
  117. self.preViewPDFView.goToNextPage(sender)
  118. }
  119. let index = self.preViewPDFView.document.index(for: self.preViewPDFView.currentPage())
  120. self.currentPageTextField.stringValue = "\(index + 1)"
  121. }
  122. @IBAction func previousPage_Action(_ sender: Any) {
  123. if self.preViewPDFView.canGoToPreviousPage() {
  124. self.preViewPDFView.goToPreviousPage(sender)
  125. }
  126. let index = self.preViewPDFView.document.index(for: self.preViewPDFView.currentPage())
  127. self.currentPageTextField.stringValue = "\(index + 1)"
  128. }
  129. override func close() {
  130. if ((self.window?.isSheet) != nil) {
  131. self.window?.sheetParent?.endSheet(self.window!)
  132. } else {
  133. super.close()
  134. }
  135. }
  136. func startExtracting() {
  137. let indeSet = self.selectIndexSet()
  138. if indeSet.count == 0 { return }
  139. let lastPathName = self.pdfDocument?.documentURL.deletingPathExtension().lastPathComponent ?? ""
  140. let tFileName = (String(format: "%@_Extract Images", lastPathName))
  141. let outputSavePanel = NSSavePanel()
  142. outputSavePanel.title = NSLocalizedString("Save as PDF", comment: "")
  143. outputSavePanel.allowsOtherFileTypes = true
  144. outputSavePanel.isExtensionHidden = true
  145. outputSavePanel.canCreateDirectories = true
  146. outputSavePanel.nameFieldStringValue = tFileName
  147. outputSavePanel.beginSheetModal(for: self.window!) {(result) in
  148. if result == NSApplication.ModalResponse.OK {
  149. self.showWaitting()
  150. DispatchQueue.main.async {
  151. let tDestFile = outputSavePanel.url?.path ?? ""
  152. let uniquePath = KMExtractImageWindowController.createDestFolder(path: tDestFile, isUnique: false)
  153. self.pdfConverter?.extractResourcesFromPDF(at: self.docPath, pdfPassword: self.password, selectIndexSet: indeSet as IndexSet, destDocPath: uniquePath, moreOptions: nil)
  154. self.extractOK(tDestFile)
  155. }
  156. }
  157. }
  158. }
  159. func extractOK(_ folder: String) {
  160. self.hideWaitting()
  161. self.close()
  162. if FileManager.default.fileExists(atPath: folder) {
  163. let workspace = NSWorkspace.shared
  164. let url = URL(fileURLWithPath: folder)
  165. workspace.activateFileViewerSelecting([url])
  166. }
  167. }
  168. func selectIndexSet() -> NSMutableIndexSet {
  169. let pageCount = self.pdfDocument?.pageCount
  170. let indeSet = NSMutableIndexSet()
  171. if self.selectPagesIndex == 0 {
  172. for i in 0..<(pageCount ?? 0) {
  173. indeSet.add(IndexSet(integer: IndexSet.Element(i)))
  174. }
  175. } else if self.selectPagesIndex == 1 {
  176. for i in 0..<(pageCount ?? 0) {
  177. if i % 2 == 0 {
  178. indeSet.add(IndexSet(integer: IndexSet.Element(i)))
  179. }
  180. }
  181. } else if self.selectPagesIndex == 2 {
  182. for i in 0..<(pageCount ?? 0) {
  183. if i % 2 != 0 {
  184. indeSet.add(IndexSet(integer: IndexSet.Element(i)))
  185. }
  186. }
  187. } else if self.selectPagesIndex == 4 {
  188. if let index = self.preViewPDFView.document?.index(for: self.preViewPDFView.currentPage()!) {
  189. indeSet.add(IndexSet(integer: IndexSet.Element(index)))
  190. }
  191. } else {
  192. let fileAttribute = KMFileAttribute()
  193. fileAttribute.filePath = self.preViewPDFView.document?.documentURL?.path ?? ""
  194. fileAttribute.bAllPage = false
  195. if (self.customPageButton.state == .on){
  196. fileAttribute.pagesType = .custom
  197. }
  198. fileAttribute.pagesString = self.rangeTextField.stringValue
  199. if fileAttribute.fetchSelectPages().isEmpty {
  200. let alert = NSAlert()
  201. alert.alertStyle = .critical
  202. alert.messageText = "\(fileAttribute.filePath.lastPathComponent) \(NSLocalizedString("Invalid page range or the page number is out of range. Please try again.", comment: ""))"
  203. alert.runModal()
  204. return indeSet
  205. }
  206. for num in fileAttribute.fetchSelectPages() {
  207. indeSet.add(num-1)
  208. }
  209. }
  210. return indeSet
  211. }
  212. class func createDestFolder(path: String, isUnique: Bool) -> String {
  213. var ret = true
  214. var tUniqueName: String? = nil
  215. let tFileManager = FileManager.default
  216. if isUnique {
  217. tUniqueName = getUniqueFilePath(filePath: path)
  218. } else {
  219. tUniqueName = path
  220. }
  221. if !tFileManager.fileExists(atPath: tUniqueName!) {
  222. do {
  223. try tFileManager.createDirectory(atPath: tUniqueName!, withIntermediateDirectories: true, attributes: nil)
  224. } catch {
  225. ret = false
  226. }
  227. }
  228. return tUniqueName!
  229. }
  230. class func getUniqueFilePath(filePath: String) -> String {
  231. var i = 0
  232. var isDirectory = ObjCBool(false)
  233. var uniqueFilePath = filePath
  234. let filemanager = FileManager.default
  235. filemanager.fileExists(atPath: uniqueFilePath, isDirectory: &isDirectory)
  236. if isDirectory.boolValue {
  237. while filemanager.fileExists(atPath: uniqueFilePath) {
  238. i += 1
  239. uniqueFilePath = "\(filePath)(\(i))"
  240. }
  241. } else {
  242. while filemanager.fileExists(atPath: uniqueFilePath) {
  243. i += 1
  244. let path = "\(filePath.deletingPathExtension)(\(i))"
  245. uniqueFilePath = path.stringByAppendingPathExtension(filePath.customPathExtension)
  246. }
  247. }
  248. return uniqueFilePath
  249. }
  250. @objc func pageChangeNotification(notification: Notification) {
  251. self.currentPageTextField.stringValue = self.preViewPDFView.currentPage().label ?? ""
  252. }
  253. func controlTextDidEndEditing(_ obj: Notification) {
  254. if obj.object as? NSTextField == self.currentPageTextField {
  255. if let intValue = Int(self.currentPageTextField.stringValue), intValue > (self.preViewPDFView.document?.pageCount ?? 0) {
  256. let alert = NSAlert()
  257. alert.alertStyle = .critical
  258. 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))
  259. alert.beginSheetModal(for: NSApp.mainWindow!, completionHandler: nil)
  260. return
  261. }
  262. self.preViewPDFView.go(to: self.preViewPDFView.document?.page(at: UInt((Int(self.currentPageTextField.stringValue) ?? 0) - 1)))
  263. } else if obj.object as? NSTextField == self.rangeTextField {
  264. if !checkPageRangeValidate(self.rangeTextField.stringValue) {
  265. let alert = NSAlert()
  266. alert.alertStyle = .critical
  267. 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))
  268. alert.beginSheetModal(for: NSApp.mainWindow!, completionHandler: nil)
  269. return
  270. }
  271. }
  272. }
  273. func checkPageRangeValidate(_ pageRangeString: String) -> Bool {
  274. let fileAttribute = KMFileAttribute()
  275. fileAttribute.filePath = self.preViewPDFView.document?.documentURL?.path ?? ""
  276. fileAttribute.bAllPage = false
  277. fileAttribute.pagesString = self.rangeTextField.stringValue
  278. if fileAttribute.fetchSelectPages().isEmpty || fileAttribute.fetchSelectPages().count < 1{
  279. return false
  280. }
  281. return true
  282. }
  283. override func mouseDown(with event: NSEvent) {
  284. super.mouseDown(with: event)
  285. self.window?.makeFirstResponder(nil)
  286. }
  287. @objc func pageChangeNotification(_ notification: Notification) {
  288. self.currentPageTextField.stringValue = self.preViewPDFView.currentPage().label ?? ""
  289. }
  290. func PDFConvertObject2(_ converter: PDFConvertObject, didEndConversion error: Error?) {
  291. self.hideWaitting()
  292. self.window?.sheetParent?.endSheet(self.window!)
  293. }
  294. func showWaitting() {
  295. if self.maskView == nil {
  296. self.maskView = KMBookletMaskView(frame: CGRect(x: 0, y: 0, width: self.window?.frame.size.width ?? 0, height: self.window?.frame.size.height ?? 0))
  297. }
  298. self.window?.contentView?.addSubview(self.maskView!)
  299. }
  300. func hideWaitting() {
  301. self.maskView?.removeFromSuperview()
  302. }
  303. func beginSheetModal(for window: NSWindow, completionHandler handler: ((NSInteger) -> Void)?) {
  304. self.window?.beginSheet(window, completionHandler: { returnCode in
  305. NSApp.endSheet(self.window!, returnCode: NSApplication.ModalResponse.abort.rawValue)
  306. if let handler = handler {
  307. handler(returnCode.rawValue)
  308. }
  309. })
  310. }
  311. }