KMExtractImageWindowController.swift 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  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. var tFileName = (String(format: "%@_Extract Images", lastPathName))
  144. let outputSavePanel = NSSavePanel()
  145. if let data = outputSavePanel.directoryURL?.appendingPathComponent(tFileName) {
  146. let fileUrl = self.fetchUniquePath(data.path)
  147. tFileName = fileUrl.lastPathComponent
  148. }
  149. outputSavePanel.title = NSLocalizedString("Save as PDF", comment: "")
  150. outputSavePanel.allowsOtherFileTypes = true
  151. outputSavePanel.isExtensionHidden = true
  152. outputSavePanel.canCreateDirectories = true
  153. outputSavePanel.nameFieldStringValue = tFileName
  154. outputSavePanel.beginSheetModal(for: self.window!) {(result) in
  155. if result == NSApplication.ModalResponse.OK {
  156. self.showWaitting()
  157. DispatchQueue.main.async {
  158. let tDestFile = outputSavePanel.url?.path ?? ""
  159. let uniquePath = KMExtractImageWindowController.createDestFolder(path: tDestFile, isUnique: false)
  160. self.pdfConverter?.extractResourcesFromPDF(at: self.docPath, pdfPassword: self.password, selectIndexSet: indeSet as IndexSet, destDocPath: uniquePath, moreOptions: nil)
  161. self.extractOK(tDestFile)
  162. }
  163. }
  164. }
  165. }
  166. func fetchUniquePath(_ originalPath: String) -> String {
  167. var path = originalPath
  168. let dManager = FileManager.default
  169. if !dManager.fileExists(atPath: path) {
  170. if path.extension.count < 1 {
  171. path = path.stringByAppendingPathExtension("pdf")
  172. }
  173. return path
  174. } else {
  175. let originalFullFileName = path.lastPathComponent
  176. let url = URL(fileURLWithPath: path)
  177. // let originalFileName = path.lastPathComponent.deletingPathExtension.lastPathComponent
  178. // let originalFileName = url.deletingPathExtension().lastPathComponent
  179. let originalFileName = originalFullFileName
  180. // let originalExtension = path.extension
  181. let startIndex: Int = 0
  182. let endIndex: Int = startIndex + originalPath.count - originalFullFileName.count - 1
  183. let fileLocatePath = originalPath.substring(to: endIndex)
  184. var i = 1
  185. while (1 != 0) {
  186. var newName = String(format: "%@(%ld)", originalFileName, i)
  187. // newName = String(format: "%@%@", newName, originalExtension)
  188. let newPath = fileLocatePath.stringByAppendingPathComponent(newName)
  189. if !dManager.fileExists(atPath: newPath) {
  190. return newPath
  191. } else {
  192. i+=1
  193. continue
  194. }
  195. }
  196. }
  197. }
  198. func extractOK(_ folder: String) {
  199. self.hideWaitting()
  200. self.close()
  201. if FileManager.default.fileExists(atPath: folder) {
  202. let workspace = NSWorkspace.shared
  203. let url = URL(fileURLWithPath: folder)
  204. workspace.activateFileViewerSelecting([url])
  205. }
  206. }
  207. func selectIndexSet() -> NSMutableIndexSet {
  208. let pageCount = self.pdfDocument?.pageCount
  209. let indeSet = NSMutableIndexSet()
  210. if self.selectPagesIndex == 0 {
  211. for i in 0..<(pageCount ?? 0) {
  212. indeSet.add(IndexSet(integer: IndexSet.Element(i)))
  213. }
  214. } else if self.selectPagesIndex == 1 {
  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 == 2 {
  221. for i in 0..<(pageCount ?? 0) {
  222. if i % 2 != 0 {
  223. indeSet.add(IndexSet(integer: IndexSet.Element(i)))
  224. }
  225. }
  226. } else if self.selectPagesIndex == 4 {
  227. if let index = self.preViewPDFView.document?.index(for: self.preViewPDFView.currentPage()!) {
  228. indeSet.add(IndexSet(integer: IndexSet.Element(index)))
  229. }
  230. } else {
  231. var fileAttribute = self.fileAttri_
  232. if fileAttribute == nil {
  233. self.fileAttri_ = KMFileAttribute()
  234. self.fileAttri_?.filePath = self.preViewPDFView.document?.documentURL?.path ?? ""
  235. fileAttribute = self.fileAttri_
  236. }
  237. fileAttribute?.bAllPage = false
  238. if (self.customPageButton.state == .on){
  239. fileAttribute?.pagesType = .custom
  240. }
  241. fileAttribute?.pagesString = self.rangeTextField.stringValue
  242. if let data = fileAttribute?.fetchSelectPages().isEmpty, data {
  243. let alert = NSAlert()
  244. alert.alertStyle = .critical
  245. alert.messageText = "\(fileAttribute?.filePath.lastPathComponent ?? "") \(NSLocalizedString("Invalid page range or the page number is out of range. Please try again.", comment: ""))"
  246. alert.runModal()
  247. return indeSet
  248. }
  249. for num in fileAttribute?.fetchSelectPages() ?? [] {
  250. indeSet.add(num-1)
  251. }
  252. }
  253. return indeSet
  254. }
  255. class func createDestFolder(path: String, isUnique: Bool) -> String {
  256. var ret = true
  257. var tUniqueName: String? = nil
  258. let tFileManager = FileManager.default
  259. if isUnique {
  260. tUniqueName = getUniqueFilePath(filePath: path)
  261. } else {
  262. tUniqueName = path
  263. }
  264. if !tFileManager.fileExists(atPath: tUniqueName!) {
  265. do {
  266. try tFileManager.createDirectory(atPath: tUniqueName!, withIntermediateDirectories: true, attributes: nil)
  267. } catch {
  268. ret = false
  269. }
  270. }
  271. return tUniqueName!
  272. }
  273. class func getUniqueFilePath(filePath: String) -> String {
  274. var i = 0
  275. var isDirectory = ObjCBool(false)
  276. var uniqueFilePath = filePath
  277. let filemanager = FileManager.default
  278. filemanager.fileExists(atPath: uniqueFilePath, isDirectory: &isDirectory)
  279. if isDirectory.boolValue {
  280. while filemanager.fileExists(atPath: uniqueFilePath) {
  281. i += 1
  282. uniqueFilePath = "\(filePath)(\(i))"
  283. }
  284. } else {
  285. while filemanager.fileExists(atPath: uniqueFilePath) {
  286. i += 1
  287. let path = "\(filePath.deletingPathExtension)(\(i))"
  288. uniqueFilePath = path.stringByAppendingPathExtension(filePath.customPathExtension)
  289. }
  290. }
  291. return uniqueFilePath
  292. }
  293. @objc func pageChangeNotification(notification: Notification) {
  294. self.currentPageTextField.stringValue = self.preViewPDFView.currentPage().label ?? ""
  295. }
  296. func controlTextDidEndEditing(_ obj: Notification) {
  297. if obj.object as? NSTextField == self.currentPageTextField {
  298. if let intValue = Int(self.currentPageTextField.stringValue), intValue > (self.preViewPDFView.document?.pageCount ?? 0) {
  299. let alert = NSAlert()
  300. alert.alertStyle = .critical
  301. 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."))
  302. alert.beginSheetModal(for: NSApp.mainWindow!, completionHandler: nil)
  303. return
  304. }
  305. self.preViewPDFView.go(to: self.preViewPDFView.document?.page(at: UInt((Int(self.currentPageTextField.stringValue) ?? 0) - 1)))
  306. } else if obj.object as? NSTextField == self.rangeTextField {
  307. if !checkPageRangeValidate(self.rangeTextField.stringValue) {
  308. let alert = NSAlert()
  309. alert.alertStyle = .critical
  310. 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."))
  311. alert.beginSheetModal(for: NSApp.mainWindow!, completionHandler: nil)
  312. return
  313. }
  314. }
  315. }
  316. func checkPageRangeValidate(_ pageRangeString: String) -> Bool {
  317. var fileAttribute = self.fileAttri_
  318. if fileAttribute == nil {
  319. self.fileAttri_ = KMFileAttribute()
  320. self.fileAttri_?.filePath = self.preViewPDFView.document?.documentURL?.path ?? ""
  321. fileAttribute = self.fileAttri_
  322. }
  323. fileAttribute?.bAllPage = false
  324. fileAttribute?.pagesString = self.rangeTextField.stringValue
  325. let isEmpty = fileAttribute?.fetchSelectPages().isEmpty ?? true
  326. let cnt = fileAttribute?.fetchSelectPages().count ?? 0
  327. if isEmpty || cnt < 1{
  328. return false
  329. }
  330. return true
  331. }
  332. override func mouseDown(with event: NSEvent) {
  333. super.mouseDown(with: event)
  334. self.window?.makeFirstResponder(nil)
  335. }
  336. @objc func pageChangeNotification(_ notification: Notification) {
  337. self.currentPageTextField.stringValue = self.preViewPDFView.currentPage().label ?? ""
  338. }
  339. func PDFConvertObject2(_ converter: PDFConvertObject, didEndConversion error: Error?) {
  340. self.hideWaitting()
  341. self.window?.sheetParent?.endSheet(self.window!)
  342. }
  343. func showWaitting() {
  344. if self.maskView == nil {
  345. self.maskView = KMBookletMaskView(frame: CGRect(x: 0, y: 0, width: self.window?.frame.size.width ?? 0, height: self.window?.frame.size.height ?? 0))
  346. }
  347. self.window?.contentView?.addSubview(self.maskView!)
  348. }
  349. func hideWaitting() {
  350. self.maskView?.removeFromSuperview()
  351. }
  352. func beginSheetModal(for window: NSWindow, completionHandler handler: ((NSInteger) -> Void)?) {
  353. self.window?.beginSheet(window, completionHandler: { returnCode in
  354. NSApp.endSheet(self.window!, returnCode: NSApplication.ModalResponse.abort.rawValue)
  355. if let handler = handler {
  356. handler(returnCode.rawValue)
  357. }
  358. })
  359. }
  360. }