KMConvertWindowController.swift 43 KB

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