KMConvertWindowController.swift 43 KB

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