KMExtractImageWindowController.swift 16 KB

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