KMConvertWindowController.swift 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979
  1. //
  2. // KMConvertWindowController.swift
  3. // PDF Reader Pro
  4. //
  5. // Created by liujiajie on 2023/11/8.
  6. //
  7. import Cocoa
  8. typealias convertBatchCallBack = () -> Void
  9. let kPreviewMaxWidth = 237.0
  10. let kPreviewMaxHeight = 325.0
  11. let kConvertFileSavePath = (kTempSavePath?.stringByAppendingPathComponent("convert.pdf"))
  12. @objcMembers class KMConvertWindowController: NSWindowController, NSTextFieldDelegate, NSWindowDelegate{
  13. @IBOutlet var prePDFViewHeight: NSLayoutConstraint!
  14. @IBOutlet var prePDFViewWidth: NSLayoutConstraint!
  15. var prePDFView: CPDFView!
  16. @IBOutlet var prePdfBGView: NSView!
  17. @IBOutlet var currentPageIndexTextField: NSTextField!
  18. @IBOutlet var totalPageCountLabel: NSTextField!
  19. @IBOutlet var formatLabel: NSTextField!
  20. @IBOutlet var formatSelectButton: NSPopUpButton!
  21. @IBOutlet var imageDPISelectButton: NSPopUpButton!
  22. @IBOutlet var moreButton: NSButton!
  23. @IBOutlet var buttonBottemOffset: NSLayoutConstraint!
  24. @IBOutlet var buttonTopOffset: NSLayoutConstraint!
  25. @IBOutlet var moreConvertBox: NSBox!
  26. @IBOutlet var moreConvertLabel: NSTextField!
  27. @IBOutlet var pageRangLabel: NSTextField!
  28. @IBOutlet var allPageButton: NSButton!
  29. @IBOutlet var currentPageButton: NSButton!
  30. @IBOutlet var oddPageButton: NSButton!
  31. @IBOutlet var evenPageButton: NSButton!
  32. @IBOutlet var handInputButton: NSButton!
  33. @IBOutlet var pageRangeTextField: NSTextField!
  34. @IBOutlet var convertButton: NSButton!
  35. @IBOutlet var cancelButton: NSButton!
  36. @IBOutlet var batchButton: NSButton!
  37. @IBOutlet var upgradeButton: NSButton!
  38. @IBOutlet var separateStypeTopOffset: NSLayoutConstraint!
  39. @IBOutlet var separateButton: NSButton!
  40. @IBOutlet var singleButton: NSButton!
  41. @IBOutlet var separateStypeBox: NSBox!
  42. @IBOutlet var extractTableButton: NSButton!
  43. @IBOutlet var extractTableTopOffset: NSLayoutConstraint!
  44. @IBOutlet var separateStypeLabel: NSTextField!
  45. @IBOutlet var excelStyleBox: NSBox!
  46. @IBOutlet var onlyTextBtn: NSButton!
  47. @IBOutlet var onlyTableBtn: NSButton!
  48. @IBOutlet var allContentBtn: NSButton!
  49. @IBOutlet var tableMenu1: NSMenuItem!
  50. @IBOutlet var tableMenu2: NSMenuItem!
  51. @IBOutlet var tableMenu3: NSMenuItem!
  52. @IBOutlet var allContentMenu2: NSMenuItem!
  53. @IBOutlet var allContentMenu3: NSMenuItem!
  54. @IBOutlet var tableMenu: NSPopUpButton!
  55. @IBOutlet var allContentMenu: NSPopUpButton!
  56. @IBOutlet var box: NSBox!
  57. var isAllInOneSheet = false
  58. var modalSession: NSApplication.ModalSession?
  59. var pdfDocument: CPDFDocument?
  60. var maskView: KMBookletMaskView?
  61. var convertType: KMConvertType = .Word
  62. var imageDPINumber: Int = 0
  63. var callBackBlock: convertBatchCallBack?
  64. var currentPage: CPDFPage?
  65. var savePath: String = ""
  66. var lockPassword: String = ""
  67. var tempPDFDocument: CPDFDocument?
  68. var excelContentOption: CPDFConvertExcelContentOptions?
  69. var excelWorksheetOption: CPDFConvertExcelWorksheetOptions?
  70. convenience init(documemtV:CPDFDocument, currentPage:CPDFPage, convertT:KMConvertType, handle:@escaping convertBatchCallBack) {
  71. self.init(windowNibName: "KMConvertWindowController")
  72. if (documemtV.documentURL != nil) {
  73. let pageIndex = documemtV.index(for: currentPage)
  74. self.pdfDocument = CPDFDocument(url: documemtV.documentURL)
  75. let isLoc: Bool = self.pdfDocument!.isLocked
  76. if (!documemtV.isLocked && isLoc) {
  77. self.lockPassword = documemtV.password
  78. self.pdfDocument?.unlock(withPassword: self.lockPassword)
  79. }
  80. self.currentPage = self.pdfDocument?.page(at: pageIndex )
  81. } else {
  82. self.pdfDocument = documemtV
  83. self.currentPage = currentPage
  84. }
  85. self.callBackBlock = handle
  86. if convertT.rawValue > 15 || convertT.rawValue < 0 {
  87. self.convertType = .Word
  88. } else {
  89. self.convertType = convertT
  90. }
  91. }
  92. convenience init(localPath:String, handle:@escaping convertBatchCallBack) {
  93. self.init(windowNibName: "KMConvertWindowController")
  94. self.pdfDocument = CPDFDocument(url: URL(fileURLWithPath: localPath))
  95. self.callBackBlock = handle
  96. let isLoc: Bool = self.pdfDocument!.isLocked
  97. if (isLoc) {
  98. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.5) {
  99. let url = self.pdfDocument?.documentURL
  100. KMBaseWindowController.checkPassword(url: url!) { [unowned self] success, resultPassword in
  101. if success {
  102. self.lockPassword = resultPassword
  103. self.pdfDocument?.unlock(withPassword: resultPassword)
  104. self.currentPage = self.pdfDocument?.page(at: 0)
  105. self.convertType = .Word
  106. }
  107. }
  108. }
  109. }
  110. }
  111. override func windowDidLoad() {
  112. super.windowDidLoad()
  113. let preView: CPDFView = CPDFView(frame: self.prePdfBGView.bounds)
  114. self.prePdfBGView.addSubview(preView)
  115. self.prePDFView = preView
  116. self.box.fillColor = .gridColor
  117. localizedLanguage()
  118. self.currentPageIndexTextField.delegate = self;
  119. self.pageRangeTextField.delegate = self;
  120. let isLoc: Bool = self.pdfDocument!.isLocked
  121. if (isLoc) {
  122. self.showWaitting()
  123. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
  124. let url = URL(fileURLWithPath: self.pdfDocument!.documentURL.path)
  125. KMBaseWindowController.checkPassword(url: url) { result, password in
  126. self.hideWaitting()
  127. if password.count > 0 {
  128. let unlockSuccess: Bool = ((self.pdfDocument?.unlock(withPassword: password)) != nil)
  129. self.lockPassword = password
  130. if unlockSuccess {
  131. self.currentPage = self.pdfDocument?.page(at: 0)
  132. }
  133. self.configuView()
  134. } else {
  135. self.buttonClicked_Cancel(self.cancelButton)
  136. }
  137. }
  138. }
  139. } else {
  140. self.configuView()
  141. }
  142. if #available(macOS 10.14, *) {
  143. let appearanceName = NSApp.effectiveAppearance.bestMatch(from: [.aqua, .darkAqua])
  144. if appearanceName == .darkAqua {
  145. moreConvertLabel.textColor = NSColor.white
  146. }
  147. }
  148. isAllInOneSheet = false
  149. separateButton.state = .on
  150. singleButton.state = .off
  151. allPageButton.state = .on
  152. allContentBtn.state = .on
  153. allContentMenu.isEnabled = true
  154. tableMenu.isEnabled = false
  155. excelContentOption = .allContent
  156. excelWorksheetOption = .forEachPage
  157. }
  158. func windowShouldClose(_ sender: NSWindow) -> Bool {
  159. self.dismissSheet(self.cancelButton)
  160. return true
  161. }
  162. func localizedLanguage() {
  163. formatLabel.stringValue = KMLocalizedString("Format:", nil)
  164. separateButton.title = KMLocalizedString("Convert each page to a separate worksheet", nil)
  165. singleButton.title = KMLocalizedString("Convert all pages to a single worksheet", nil)
  166. box.title = KMLocalizedString("Page Range:", nil)
  167. separateStypeLabel.stringValue = KMLocalizedString("Excel Worksheet Settings", nil)
  168. extractTableButton.title = KMLocalizedString("Extract Tables Only", nil)
  169. allPageButton.title = KMLocalizedString("All Pages", nil)
  170. currentPageButton.title = KMLocalizedString("Current Page", nil)
  171. oddPageButton.title = KMLocalizedString("Odd Pages Only", nil)
  172. evenPageButton.title = KMLocalizedString("Even Pages Only", nil)
  173. pageRangeTextField.placeholderString = KMLocalizedString("e.g. 1,3-5,10", nil)
  174. batchButton.title = KMLocalizedString("Batch", nil)
  175. cancelButton.title = KMLocalizedString("Cancel", nil)
  176. convertButton.title = KMLocalizedString("Convert", nil)
  177. upgradeButton.title = KMLocalizedString("Upgrade", nil)
  178. onlyTextBtn.title = KMLocalizedString("Only Text", nil)
  179. onlyTableBtn.title = KMLocalizedString("Only Table", nil)
  180. allContentBtn.title = KMLocalizedString("All Content", nil)
  181. tableMenu1.title = KMLocalizedString("Create Sheet for each Table", nil)
  182. tableMenu2.title = KMLocalizedString("Create Sheet for each Page", nil)
  183. allContentMenu2.title = KMLocalizedString("Create Sheet for each Page", nil)
  184. tableMenu3.title = KMLocalizedString("Create single Sheet for File", nil)
  185. allContentMenu3.title = KMLocalizedString("Create single Sheet for File", nil)
  186. }
  187. func hideWaitting() {
  188. maskView?.removeFromSuperview()
  189. }
  190. func showWaitting() {
  191. if maskView == nil {
  192. maskView = KMBookletMaskView(frame: CGRect(x: 0, y: 0, width: self.window?.frame.size.width ?? 0, height: self.window?.frame.size.height ?? 0))
  193. }
  194. self.window?.contentView?.addSubview(maskView!)
  195. }
  196. func configuView() {
  197. self.prePDFView.autoScales = true
  198. self.prePDFView.wantsLayer = true
  199. self.prePDFView.document = self.pdfDocument
  200. self.imageDPISelectButton.removeAllItems()
  201. self.formatSelectButton.removeAllItems()
  202. let dpiArray = ["50 dpi", "72 dpi", "96 dpi", "150 dpi", "300 dpi", "600 dpi"]
  203. let formArray = ["Excel (.xlsx)", "PowerPoint (.pptx)", "RTF (.rtf)", "CSV (.csv)", "Html (.html)", "Text (.txt)", "JPEG (.jpeg)", "JPG (.jpg)", "PNG (.png)", "GIF (.gif)", "TIFF (.tiff)", "TGA (.tga)", "BMP (.bmp)", "JPEG-2000 (.jp2)"]
  204. for (index, string) in formArray.enumerated() {
  205. let item = NSMenuItem()
  206. item.title = string
  207. item.target = self
  208. item.tag = index + 1
  209. self.formatSelectButton.menu?.addItem(item)
  210. }
  211. var isShowAdvanced = false
  212. let wordItem = NSMenuItem()
  213. wordItem.title = "Word (.docx)"
  214. wordItem.target = self
  215. var isShowUpgrade = false
  216. var convertSample: KMConvertType = .Word
  217. #if VERSION_FREE
  218. #if VERSION_DMG
  219. // 桌机版
  220. wordItem.tag = convertSample.rawValue
  221. isShowAdvanced = true
  222. if IAPProductsManager.default().isAvailableAllFunction() {
  223. if IAPProductsManager.default().isAvailableAdvancedPDFToOffice() {
  224. convertSample = .AdvancedWord
  225. wordItem.tag = convertSample.rawValue
  226. isShowAdvanced = false
  227. } else {
  228. isShowUpgrade = true
  229. }
  230. } else {
  231. isShowUpgrade = true
  232. }
  233. #else
  234. // 免费版
  235. convertSample = .Word
  236. wordItem.tag = convertSample.rawValue
  237. isShowAdvanced = true
  238. if IAPProductsManager.default().isAvailableAllFunction() {
  239. if IAPProductsManager.default().isAvailableAdvancedPDFToOffice() {
  240. convertSample = .AdvancedWord
  241. wordItem.tag = convertSample.rawValue
  242. isShowAdvanced = false
  243. } else {
  244. isShowUpgrade = true
  245. }
  246. } else {
  247. isShowUpgrade = true
  248. }
  249. #endif
  250. #else
  251. convertSample = .Word
  252. wordItem.tag = convertSample.rawValue
  253. // 付费版
  254. isShowAdvanced = true
  255. if IAPProductsManager.default().isAvailableAdvancedPDFToOffice() {
  256. isShowAdvanced = false
  257. convertSample = .AdvancedWord
  258. wordItem.tag = convertSample.rawValue
  259. } else {
  260. isShowUpgrade = true
  261. }
  262. #endif
  263. if wordItem.title != "" {
  264. if isShowAdvanced {
  265. let originStr = " \(KMLocalizedString("Standard", nil)) "
  266. let str = KMLocalizedString("Word (.docx)", nil)
  267. let attributedStr = NSMutableAttributedString(string: "\(str) \(originStr)")
  268. attributedStr.addAttribute(NSAttributedString.Key.backgroundColor, value: NSColor(red: 40/255.0, green: 193.0/255.0, blue: 107.0/255.0, alpha: 1.0), range: NSMakeRange(str.count + 2, originStr.count))
  269. attributedStr.addAttribute(NSAttributedString.Key.foregroundColor, value: NSColor.white, range: NSMakeRange(str.count + 2, originStr.count))
  270. let item = NSMenuItem()
  271. item.attributedTitle = attributedStr
  272. item.target = self
  273. item.tag = wordItem.tag
  274. self.formatSelectButton.menu?.insertItem(item, at: 0)
  275. } else {
  276. self.formatSelectButton.menu?.insertItem(wordItem, at: 0)
  277. }
  278. }
  279. if !isShowUpgrade {
  280. self.upgradeButton.isHidden = true
  281. }
  282. var selectIndex = 0
  283. if isShowAdvanced {
  284. let originStr = " \(NSLocalizedString("Advanced", comment: "")) "
  285. let str = NSLocalizedString("Word (.docx)", comment: "")
  286. let attributedStr = NSMutableAttributedString(string: "\(str) \(originStr)")
  287. attributedStr.addAttribute(NSAttributedString.Key.backgroundColor, value: NSColor(red: 245.0/255.0, green: 142.0/255.0, blue: 38.0/255.0, alpha: 1.0), range: NSMakeRange(str.count + 2, originStr.count))
  288. attributedStr.addAttribute(NSAttributedString.Key.foregroundColor, value: NSColor.white, range: NSMakeRange(str.count + 2, originStr.count))
  289. let item = NSMenuItem()
  290. item.attributedTitle = attributedStr
  291. item.target = self
  292. convertSample = .AdvancedWord
  293. item.tag = convertSample.rawValue
  294. self.formatSelectButton.menu?.insertItem(item, at: 0)
  295. }
  296. if self.convertType == .Word {
  297. selectIndex = 0
  298. } else {
  299. selectIndex = self.convertType.rawValue
  300. if isShowAdvanced {
  301. selectIndex += 1
  302. }
  303. if wordItem.title == "" {
  304. selectIndex -= 1
  305. }
  306. }
  307. self.formatSelectButton.selectItem(at: selectIndex)
  308. let item = self.formatSelectButton.selectedItem
  309. self.convertType = KMConvertType(rawValue: item?.tag ?? 0) ?? .Word
  310. self.imageDPISelectButton.isHidden = true
  311. self.buttonTopOffset.constant = -26
  312. self.imageDPISelectButton.addItems(withTitles: dpiArray)
  313. self.imageDPISelectButton.selectItem(at: 3)
  314. self.imageDPINumber = 150
  315. self.totalPageCountLabel.stringValue = " / \(self.pdfDocument?.pageCount ?? 1)"
  316. self.totalPageCountLabel.textColor = KMAppearance.Layout.h2Color()
  317. self.updataView()
  318. self.prePDFView.go(to: currentPage)
  319. let pageIndex = self.prePDFView.document.index(for: self.prePDFView.currentPage()!)+1
  320. self.currentPageIndexTextField.stringValue = "\(pageIndex)"
  321. if let documentURL = self.pdfDocument?.documentURL{
  322. self.pdfDocument = CPDFDocument(url: documentURL)
  323. if !lockPassword.isEmpty && lockPassword.count > 0{
  324. self.pdfDocument?.unlock(withPassword: lockPassword)
  325. }
  326. self.prePDFView.document = self.pdfDocument
  327. }
  328. self.prePDFView.setDisplay(.singlePage)
  329. self.prePDFView.layoutDocumentView()
  330. }
  331. func updataView() {
  332. var moreLabelString: String = ""
  333. var offset: CGFloat = 0
  334. excelStyleBox.isHidden = true
  335. #if VERSION_FREE
  336. // 座机版
  337. if !(IAPProductsManager.default().isAvailableAllFunction()) {
  338. moreLabelString = KMLocalizedString("The first 10 pages for free. More precise one.", nil)
  339. } else {
  340. if !(IAPProductsManager.default().isAvailableAdvancedPDFToOffice()) {
  341. if .Word == self.convertType {
  342. moreLabelString = KMLocalizedString("Export PDF to Word and other Microsoft Office formats", nil)
  343. } else if self.convertType == .AdvancedWord ||
  344. .Excel == self.convertType ||
  345. .PPT == self.convertType ||
  346. .CSV == self.convertType ||
  347. .RTF == self.convertType ||
  348. .GIF == self.convertType ||
  349. .TIFF == self.convertType ||
  350. .JP2 == self.convertType ||
  351. .BMP == self.convertType ||
  352. .TGA == self.convertType {
  353. moreLabelString = KMLocalizedString("The first 10 pages for free. More precise one.", nil)
  354. }
  355. }
  356. }
  357. #else
  358. // 付费版
  359. if !(IAPProductsManager.default().isAvailableAdvancedPDFToOffice()) {
  360. if .Word == self.convertType {
  361. moreLabelString = KMLocalizedString("Export PDF to Word and other Microsoft Office formats", nil)
  362. } else if self.convertType == .AdvancedWord ||
  363. .Excel == self.convertType ||
  364. .PPT == self.convertType ||
  365. .CSV == self.convertType ||
  366. .RTF == self.convertType ||
  367. .GIF == self.convertType ||
  368. .TIFF == self.convertType ||
  369. .JP2 == self.convertType ||
  370. .BMP == self.convertType ||
  371. .TGA == self.convertType {
  372. moreLabelString = KMLocalizedString("The first 10 pages for free. More precise one.", nil)
  373. }
  374. }
  375. #endif
  376. if convertType.rawValue >= 7 && convertType.rawValue <= 14 {
  377. offset += imageDPISelectButton.frame.size.height
  378. imageDPISelectButton.isHidden = false
  379. buttonTopOffset.constant = 5
  380. } else {
  381. imageDPISelectButton.isHidden = true
  382. buttonTopOffset.constant = -26
  383. }
  384. if moreLabelString.count < 1 {
  385. offset += 5
  386. moreConvertBox.isHidden = true
  387. moreButton.isHidden = true
  388. } else {
  389. offset += (moreButton.frame.size.height + 5)
  390. moreConvertBox.isHidden = false
  391. moreButton.isHidden = false
  392. moreConvertLabel.stringValue = moreLabelString
  393. }
  394. if .Excel == convertType {
  395. separateStypeTopOffset.constant = separateStypeBox.frame.size.height + 58 + 16
  396. extractTableTopOffset.constant = separateStypeBox.frame.size.height + 50
  397. separateStypeBox.isHidden = true
  398. extractTableButton.isHidden = true
  399. excelStyleBox.isHidden = false
  400. separateStypeLabel.isHidden = false
  401. separateStypeLabel.stringValue = NSLocalizedString("Excel Worksheet Settings", comment: "")
  402. separateButton.title = NSLocalizedString("Convert each page to a separate worksheet", comment: "")
  403. singleButton.title = NSLocalizedString("Convert all pages to a single worksheet", comment: "")
  404. buttonClicked_extractTable(extractTableButton)
  405. } else if .AdvancedWord == convertType {
  406. singleButton.setTitleColor(NSColor.labelColor)
  407. separateButton.setTitleColor(NSColor.labelColor)
  408. separateStypeLabel.textColor = NSColor.labelColor
  409. separateButton.state = NSControl.StateValue.on
  410. singleButton.isEnabled = true
  411. separateButton.isEnabled = true
  412. isAllInOneSheet = false
  413. separateStypeTopOffset.constant = separateStypeBox.frame.size.height + 40
  414. extractTableButton.isHidden = true
  415. separateStypeBox.isHidden = false
  416. separateStypeLabel.isHidden = false
  417. separateStypeLabel.stringValue = NSLocalizedString("Layout Settings", comment: "")
  418. separateButton.title = NSLocalizedString("Retain Flowing Text", comment: "")
  419. singleButton.title = NSLocalizedString("Retain Page Layout", comment: "")
  420. } else if .CSV == convertType {
  421. separateStypeTopOffset.constant = extractTableButton.frame.size.height + 30
  422. extractTableTopOffset.constant = 12
  423. extractTableButton.isHidden = false
  424. separateStypeBox.isHidden = true
  425. separateStypeLabel.isHidden = true
  426. } else {
  427. separateStypeTopOffset.constant = 15
  428. separateStypeBox.isHidden = true
  429. extractTableButton.isHidden = true
  430. separateStypeLabel.isHidden = true
  431. }
  432. buttonBottemOffset.constant = offset
  433. }
  434. @IBAction func buttonClicked_extractTable(_ sender: NSButton) {
  435. if extractTableButton.state == .on {
  436. singleButton.setTitleColor(KMAppearance.Layout.b15_1Color())
  437. separateButton.setTitleColor(KMAppearance.Layout.b15_1Color())
  438. separateStypeLabel.textColor = KMAppearance.Layout.b15_1Color()
  439. singleButton.isEnabled = false
  440. separateButton.isEnabled = false
  441. separateButton.state = .off
  442. singleButton.state = .off
  443. } else {
  444. singleButton.setTitleColor(NSColor.labelColor)
  445. separateButton.setTitleColor(NSColor.labelColor)
  446. separateStypeLabel.textColor = NSColor.labelColor
  447. separateButton.state = .on
  448. singleButton.isEnabled = true
  449. separateButton.isEnabled = true
  450. isAllInOneSheet = false
  451. }
  452. }
  453. @IBAction func buttonClicked_Cancel(_ sender: NSButton) {
  454. if FileManager.default.fileExists(atPath: kConvertFileSavePath ?? "") {
  455. do {
  456. try FileManager.default.removeItem(atPath: kConvertFileSavePath ?? "")
  457. } catch {
  458. print("Error removing item at path: (error.localizedDescription)")
  459. }
  460. }
  461. dismissSheet(sender)
  462. }
  463. func dismissSheet(_ sender: NSButton) {
  464. // if #available(macOS 10.13, *) {
  465. // self.window?.endSheet(sender.window!)
  466. // } else {
  467. // NSApp.endSheet(self.window!)
  468. // }
  469. // self.window?.orderOut(self)
  470. self.km_quick_endSheet()
  471. }
  472. func showCriticalAlert(_ alertMsg: String?) {
  473. let alert = NSAlert()
  474. alert.alertStyle = .critical
  475. if let msg = alertMsg {
  476. alert.informativeText = msg
  477. } else {
  478. let st = self.pdfDocument?.documentURL.lastPathComponent.count ?? 0 > 0 ? self.pdfDocument?.documentURL.lastPathComponent : KMLocalizedString("Untitled.pdf", nil)
  479. alert.messageText = String(format: "%@ %@", st!, KMLocalizedString("Invalid page range or the page number is out of range. Please try again.", nil))
  480. }
  481. alert.runModal()
  482. }
  483. func produceNewPDF(with pagesArray: [CPDFPage]) {
  484. if tempPDFDocument != nil{
  485. tempPDFDocument = nil
  486. }
  487. tempPDFDocument = CPDFDocument()
  488. for i in 0..<(self.pdfDocument?.pageCount ?? 0) {
  489. tempPDFDocument?.removePage(at: i)
  490. }
  491. for addedPage in pagesArray {
  492. tempPDFDocument?.insertPageObject(addedPage, at: tempPDFDocument!.pageCount)
  493. }
  494. self.prePDFView.document = tempPDFDocument
  495. self.prePDFView.goToFirstPage(nil)
  496. self.currentPageIndexTextField.stringValue = "1"
  497. self.totalPageCountLabel.stringValue = " / \(tempPDFDocument!.pageCount)"
  498. }
  499. func pageRangeSetON(_ sender: NSButton) {
  500. allPageButton.state = .off
  501. oddPageButton.state = .off
  502. evenPageButton.state = .off
  503. handInputButton.state = .off
  504. currentPageButton.state = .off
  505. sender.state = .on
  506. if sender == handInputButton {
  507. pageRangeTextField.isEditable = true
  508. pageRangeTextField.isSelectable = true
  509. // self.pageRangeTextField.textColor = NSColor.textColor
  510. window?.makeFirstResponder(pageRangeTextField)
  511. } else {
  512. pageRangeTextField.isEditable = false
  513. pageRangeTextField.isSelectable = false
  514. // self.pageRangeTextField.textColor = NSColor.lightGrayColor
  515. window?.makeFirstResponder(self)
  516. }
  517. }
  518. @IBAction func buttonClicked_FormatSelect(_ sender: NSButton) {
  519. guard let item = self.formatSelectButton.selectedItem else { return }
  520. self.convertType = KMConvertType(rawValue: item.tag) ?? .Word
  521. updataView()
  522. }
  523. func transform(with string: String) {
  524. if string == KMLocalizedString("Create Sheet for each Table", nil) {
  525. self.excelWorksheetOption = .forEachTable
  526. } else if string == KMLocalizedString("Create Sheet for each Page", nil) {
  527. self.excelWorksheetOption = .forEachPage
  528. } else if string == KMLocalizedString("Create single Sheet for File", nil) {
  529. self.excelWorksheetOption = .forTheDocument
  530. }
  531. }
  532. @IBAction func buttonClicked_excelStyle(_ sender: NSButton) {
  533. if sender.isEqual(self.onlyTextBtn) {
  534. self.tableMenu.isEnabled = false
  535. self.allContentMenu.isEnabled = false
  536. self.excelContentOption = .onlyText
  537. self.excelWorksheetOption = .forEachTable
  538. } else if (sender.isEqual(self.onlyTableBtn)) {
  539. self.tableMenu.isEnabled = true
  540. self.allContentMenu.isEnabled = false
  541. self.excelContentOption = .onlyTable
  542. transform(with: self.tableMenu.selectedItem?.title ?? "")
  543. } else if (sender.isEqual(self.allContentBtn)) {
  544. self.tableMenu.isEnabled = false
  545. self.allContentMenu.isEnabled = true
  546. self.excelContentOption = .allContent
  547. transform(with: self.allContentMenu.selectedItem?.title ?? "")
  548. }
  549. }
  550. @IBAction func buttonClicked_tableMenu(_ sender: NSButton) {
  551. transform(with: self.tableMenu.selectedItem?.title ?? "")
  552. }
  553. @IBAction func buttonClicked_allContentMenu(_ sender: NSButton) {
  554. transform(with: self.allContentMenu.selectedItem?.title ?? "")
  555. }
  556. @IBAction func buttonClicked_PageSelect(_ sender: NSButton) {
  557. pageRangeSetON(sender)
  558. self.lockPassword = ""
  559. let pagesArray = NSMutableArray()
  560. for i in 0..<(self.pdfDocument?.pageCount ?? 0) {
  561. let copyPage = self.pdfDocument?.page(at: i)
  562. pagesArray.add(copyPage!)
  563. }
  564. if sender.isEqual(self.oddPageButton) {
  565. pagesArray.subArray(type: .Odd)
  566. } else if (sender.isEqual(self.evenPageButton)) {
  567. pagesArray.subArray(type: .Even)
  568. } else if (sender.isEqual(self.currentPageButton)) {
  569. pagesArray.removeAllObjects()
  570. let page = self.prePDFView.currentPage()
  571. if (page != nil) {
  572. pagesArray.add(page as Any)
  573. }
  574. }
  575. produceNewPDF(with: pagesArray as! [CPDFPage])
  576. // perform(#selector(produceNewPDF(with:)), with: pagesArray, afterDelay: 2)
  577. // performSelector(produceNewPDF(with:), withObject: pagesArray, afterDelay: 2)
  578. }
  579. @IBAction func buttonClicked_DpiSelect(_ sender: NSPopUpButton) {
  580. let index = sender.indexOfSelectedItem
  581. var dpi = 0
  582. if index == 0 {
  583. dpi = 50
  584. } else if index == 1 {
  585. dpi = 72
  586. } else if index == 2 {
  587. dpi = 96
  588. } else if index == 3 {
  589. dpi = 150
  590. } else if index == 4 {
  591. dpi = 300
  592. } else if index == 5 {
  593. dpi = 600
  594. }
  595. self.imageDPINumber = dpi
  596. }
  597. @IBAction func buttonClick_PreviousPage(_ sender: NSButton) {
  598. if self.prePDFView.canGoToPreviousPage() {
  599. self.prePDFView.goToPreviousPage(nil)
  600. let currentIndex = self.prePDFView.document?.index(for: self.prePDFView.currentPage()) ?? 0
  601. self.currentPageIndexTextField.stringValue = "\(currentIndex + 1)"
  602. }
  603. }
  604. @IBAction func buttonClicked_NextPage(_ sender: NSButton) {
  605. if self.prePDFView.canGoToNextPage() {
  606. self.prePDFView.goToNextPage(nil)
  607. let currentIndex = self.prePDFView.document?.index(for: self.prePDFView.currentPage())
  608. self.currentPageIndexTextField.stringValue = "\((currentIndex ?? 0) + 1)"
  609. }
  610. }
  611. @IBAction func buttonClicked_Batch(_ sender: NSButton) {
  612. if !IAPProductsManager.default().isAvailableAllFunction() {
  613. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  614. return
  615. }
  616. if self.pdfDocument?.documentURL == nil {
  617. NSSound.beep()
  618. return
  619. }
  620. if self.callBackBlock != nil {
  621. self.callBackBlock!()
  622. self.callBackBlock = nil
  623. }
  624. dismissSheet(sender)
  625. }
  626. @IBAction func buttonClicked_Convert(_ sender: Any) {
  627. self.window?.makeFirstResponder(self.prePDFView)
  628. if self.handInputButton.state == .on {
  629. let fileAttribute = KMFileAttribute()
  630. fileAttribute.pdfDocument = self.pdfDocument
  631. fileAttribute.filePath = self.pdfDocument?.documentURL.path ?? ""
  632. fileAttribute.bAllPage = false
  633. if self.handInputButton.state == .on {
  634. fileAttribute.pagesType = .custom
  635. }
  636. fileAttribute.pagesString = self.pageRangeTextField.stringValue
  637. if fileAttribute.fetchSelectPages().isEmpty {
  638. return
  639. }
  640. }
  641. let openPanel = NSOpenPanel()
  642. openPanel.canChooseFiles = false
  643. openPanel.canChooseDirectories = true
  644. openPanel.canCreateDirectories = true
  645. openPanel.beginSheetModal(for: self.window!) { result in
  646. if result == .OK {
  647. self.savePath = openPanel.url!.path
  648. self.beginConvert()
  649. }
  650. }
  651. }
  652. func beginConvert() {
  653. var isLimitConvert = false
  654. if (KMLightMemberManager.manager.canPayFunction() == false) {
  655. if self.convertType == .PNG ||
  656. .JPEG == self.convertType ||
  657. .JPG == self.convertType ||
  658. .HTML == self.convertType ||
  659. .Text == self.convertType ||
  660. .Word == self.convertType {
  661. isLimitConvert = false
  662. } else {
  663. isLimitConvert = true
  664. }
  665. }
  666. self.showWaitting()
  667. let pages = NSMutableArray()
  668. DispatchQueue.global(qos: .background).async { [self] in
  669. let filePath = getConvertFileSavePath()
  670. if (FileManager.default.fileExists(atPath: filePath)) {
  671. try?FileManager.default.removeItem(atPath: filePath)
  672. }
  673. if self.prePDFView.document.write(toFile: filePath) {
  674. for i in 0..<self.prePDFView.document.pageCount {
  675. pages.add(i + 1)
  676. }
  677. }
  678. DispatchQueue.main.async {
  679. if pages.count < 1 {
  680. self.hideWaitting()
  681. let alert = NSAlert()
  682. alert.alertStyle = .critical
  683. alert.messageText = "\(self.pdfDocument?.documentURL.path.lastPathComponent ?? NSLocalizedString("Untitled", comment: "")) \(NSLocalizedString("Invalid page range or the page number is out of range. Please try again.", comment: ""))"
  684. alert.runModal()
  685. return
  686. }
  687. let pageCount = pages.count
  688. var selectPages = [Int]()
  689. if isLimitConvert {
  690. if pageCount >= 10 {
  691. for i in 0..<10 {
  692. selectPages.append(pages[i] as! Int)
  693. }
  694. } else {
  695. selectPages = pages as! [Int]
  696. }
  697. } else {
  698. selectPages = pages as! [Int]
  699. }
  700. let convert = KMPDFConvert()
  701. convert.filePath = filePath
  702. convert.pages = selectPages
  703. convert.isAllInOneSheet = self.isAllInOneSheet
  704. if self.convertType == .Word {
  705. convert.type = 0
  706. } else {
  707. convert.type = 1
  708. }
  709. convert.isExtractTable = self.extractTableButton.state == .on
  710. convert.outputFolderPath = self.savePath
  711. convert.outputFileName = (self.pdfDocument?.documentURL.deletingPathExtension().lastPathComponent) ?? NSLocalizedString("Untitled", comment: "")
  712. if self.convertType == .AdvancedWord {
  713. convert.convertType = .word
  714. } else if self.convertType == .JPEG ||
  715. self.convertType == .JPG ||
  716. self.convertType == .PNG ||
  717. self.convertType == .GIF ||
  718. self.convertType == .TIFF ||
  719. self.convertType == .TGA ||
  720. self.convertType == .BMP ||
  721. self.convertType == .JP2 {
  722. convert.convertType = KMPDFConvertType(rawValue: self.convertType.rawValue) ?? .word
  723. convert.options = [KMPDFConvertOptionsKeyImageDPI : self.imageDPINumber,
  724. KMPDFConvertOptionsKeyImageWithAnnotation : true] as [String : Any]
  725. } else {
  726. convert.convertType = KMPDFConvertType(rawValue: self.convertType.rawValue) ?? .word
  727. }
  728. if self.convertType == .Excel {
  729. convert.excelContentOption = self.excelContentOption
  730. convert.excelWorksheetOption = self.excelWorksheetOption
  731. }
  732. convert.password = self.lockPassword
  733. KMPDFConvertManager.defaultManager.convert(convert: convert) { [self] (finished, error) in
  734. self.hideWaitting()
  735. if finished {
  736. self.buttonClicked_Cancel(cancelButton)
  737. if FileManager.default.fileExists(atPath: convert.outputFilePath) {
  738. let workspace = NSWorkspace.shared
  739. let url = URL(fileURLWithPath: convert.outputFilePath)
  740. workspace.activateFileViewerSelecting([url])
  741. }
  742. } else if let error = error {
  743. let err: NSError = error as NSError
  744. var erroeString = ""
  745. switch err.code {
  746. case CPDFConverterEncryptError:
  747. erroeString = NSLocalizedString("Password required or incorrect password. Please re-enter your password and try again", comment: "")
  748. break
  749. case CPDFConverterPermissionError:
  750. erroeString = NSLocalizedString("The license doesn't allow the permission", comment: "")
  751. break
  752. case CPDFConverterMallocError:
  753. erroeString = NSLocalizedString("Malloc failure", comment: "")
  754. break
  755. case CPDFConverterUnknownError:
  756. erroeString = NSLocalizedString("Unknown error in processing conversion. Please try again later", comment: "")
  757. break
  758. case CPDFConverterPDFUnknownError:
  759. erroeString = NSLocalizedString("Unknown error in processing PDF. Please try again later", comment: "")
  760. break
  761. case CPDFConverterPDFFileError:
  762. erroeString = NSLocalizedString("File not found or could not be opened. Check if your file exists or choose another file to convert", comment: "")
  763. break
  764. case CPDFConverterPDFFormatError:
  765. erroeString = NSLocalizedString("File not in PDF format or corruptead. Change a PDF file and try again", comment: "")
  766. break
  767. case CPDFConverterPDFSecurityError:
  768. erroeString = NSLocalizedString("Unsupported security scheme", comment: "")
  769. break
  770. case CPDFConverterPDFPageError:
  771. erroeString = NSLocalizedString("Page not found or content error", comment: "")
  772. break
  773. default:
  774. erroeString = NSLocalizedString("Table not found", comment: "")
  775. break
  776. }
  777. let alert = NSAlert()
  778. alert.alertStyle = .critical
  779. alert.messageText = NSLocalizedString("Conversion Failed", comment: "")
  780. alert.informativeText = erroeString
  781. alert.addButton(withTitle: NSLocalizedString("OK", comment: ""))
  782. if #available(OSX 10.14, *) {
  783. alert.beginSheetModal(for: self.window!, completionHandler: nil)
  784. } else {
  785. alert.runModal()
  786. }
  787. }
  788. }
  789. }
  790. }
  791. }
  792. func getConvertFileSavePath() -> String {
  793. var path = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.applicationSupportDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).last
  794. path?.append("/")
  795. path?.append(Bundle.main.bundleIdentifier!)
  796. if (FileManager.default.fileExists(atPath: path!) == false) {
  797. try?FileManager.default.createDirectory(atPath: path!, withIntermediateDirectories: false)
  798. }
  799. path?.append("/")
  800. path?.append("convert.pdf")
  801. return path!
  802. }
  803. @IBAction func buttonClicked_MoreConvert(_ sender: Any) {
  804. #if VERSION_DMG
  805. if IAPProductsManager.default().isAvailableAllFunction() && !IAPProductsManager.default().isAvailableAdvancedPDFToOffice() {
  806. let limitWC = KMPurchaseLimitWindowController.currentLimitWC()
  807. limitWC.continueBlock = { windowController in
  808. }
  809. limitWC.window?.center()
  810. limitWC.showWindow(nil)
  811. } else {
  812. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  813. }
  814. #else
  815. if IAPProductsManager.default().isAvailableAllFunction() {
  816. var vc: KMToolCompareWindowController? = nil
  817. if convertType == .Word || convertType == .AdvancedWord {
  818. // vc = KMToolCompareWindowController(toolType: .Convert, selectNum: 1)
  819. vc = KMToolCompareWindowController.toolCompare(toolType: .Convert, selectNum: 1)
  820. } else if convertType == .Excel {
  821. // vc = KMToolCompareWindowController(toolType: .Convert, selectNum: 2)
  822. vc = KMToolCompareWindowController.toolCompare(toolType: .Convert, selectNum: 2)
  823. } else if convertType == .PPT {
  824. // vc = KMToolCompareWindowController(toolType: .Convert, selectNum: 3)
  825. vc = KMToolCompareWindowController.toolCompare(toolType: .Convert, selectNum: 3)
  826. } else if convertType.rawValue < 15 && convertType.rawValue > 7 {
  827. // vc = KMToolCompareWindowController(toolType: .Convert, selectNum: 4)
  828. vc = KMToolCompareWindowController.toolCompare(toolType: .Convert, selectNum: 4)
  829. } else {
  830. // vc = KMToolCompareWindowController(toolType: .Convert, selectNum: 0)
  831. vc = KMToolCompareWindowController.toolCompare(toolType: .Convert, selectNum: 0)
  832. }
  833. vc?.showWindow(nil)
  834. } else {
  835. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  836. }
  837. #endif
  838. self.buttonClicked_Cancel(self.cancelButton)
  839. }
  840. @IBAction func buttonItemClick_SepSingle(_ sender: Any) {
  841. if .on == self.singleButton.state {
  842. self.isAllInOneSheet = true
  843. } else {
  844. self.isAllInOneSheet = false
  845. }
  846. }
  847. func controlTextDidEndEditing(_ obj: Notification) {
  848. let object = obj.object
  849. if (object as AnyObject).isEqual(self.currentPageIndexTextField) == true {
  850. let num: Int = Int(self.currentPageIndexTextField.stringValue) ?? 1
  851. let targetPage = self.prePDFView.document.page(at: UInt(num - 1))
  852. self.prePDFView.go(to: targetPage)
  853. } else if (object as AnyObject).isEqual(self.pageRangeTextField) == true {
  854. guard self.handInputButton.state == .on else { return }
  855. let fileAttribute = KMFileAttribute()
  856. fileAttribute.pdfDocument = self.pdfDocument
  857. fileAttribute.bAllPage = false
  858. fileAttribute.pagesType = .custom
  859. fileAttribute.pagesString = self.pageRangeTextField.stringValue
  860. if fileAttribute.fetchSelectPages().count > 0 {
  861. let pagesArray = NSMutableArray()
  862. for pageNum in fileAttribute.fetchSelectPages() {
  863. let tpage = self.pdfDocument?.page(at: UInt(pageNum - 1))
  864. pagesArray.add(tpage as Any)
  865. }
  866. self.produceNewPDF(with: pagesArray as! [CPDFPage])
  867. } else {
  868. self.showCriticalAlert(nil)
  869. }
  870. }
  871. }
  872. func controlTextDidChange(_ obj: Notification) {
  873. if let textField = obj.object as? NSTextField {
  874. if textField.isEqual(self.currentPageIndexTextField) {
  875. if let stringValue = self.currentPageIndexTextField.formatter?.string(for: NSNumber(value: Float(self.currentPageIndexTextField.stringValue) ?? 0)) {
  876. if let integerValue = Int(stringValue) {
  877. var string = stringValue
  878. if integerValue > self.prePDFView.document.pageCount {
  879. string = "(self.prePDFView.document.pageCount)"
  880. } else if integerValue <= 0 {
  881. string = "1"
  882. }
  883. self.currentPageIndexTextField.stringValue = string
  884. }
  885. }
  886. }
  887. }
  888. }
  889. }
  890. @objc enum KMSubArrayType: Int {
  891. case Odd = 0
  892. case Even
  893. }
  894. extension NSMutableArray{
  895. func subArray(type: KMSubArrayType) {
  896. if self.count == 0 { return }
  897. if type.rawValue > 1 || type.rawValue < 0 { return }
  898. let newArray = NSMutableArray()
  899. for i in 0..<self.count {
  900. if i % 2 == type.rawValue {
  901. newArray.add(self[i])
  902. }
  903. }
  904. self.removeAllObjects()
  905. self.addObjects(from: newArray as! [Any])
  906. }
  907. }