KMExtractImageWindowController.swift 15 KB

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