KMConvertWindowController.swift 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018
  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 = String(format: "%@ %@", KMLocalizedString("The first 10 pages for free"), KMLocalizedString("Unlimited Convert"))
  339. } else {
  340. if !IAPProductsManager.default().isAvailableAdvancedPDFToOffice() {
  341. if .Word == self.convertType ||
  342. self.convertType == .AdvancedWord ||
  343. .Excel == self.convertType ||
  344. .PPT == self.convertType ||
  345. .CSV == self.convertType ||
  346. .RTF == self.convertType ||
  347. .GIF == self.convertType ||
  348. .TIFF == self.convertType ||
  349. .JP2 == self.convertType ||
  350. .BMP == self.convertType ||
  351. .TGA == self.convertType {
  352. moreLabelString = String(format: "%@ %@", KMLocalizedString("The first 10 pages for free"), KMLocalizedString("Unlimited Convert"))
  353. }
  354. }
  355. }
  356. #else
  357. // 付费版
  358. if !(IAPProductsManager.default().isAvailableAdvancedPDFToOffice()) {
  359. if .Word == self.convertType ||
  360. self.convertType == .AdvancedWord ||
  361. .Excel == self.convertType ||
  362. .PPT == self.convertType ||
  363. .CSV == self.convertType ||
  364. .RTF == self.convertType ||
  365. .GIF == self.convertType ||
  366. .TIFF == self.convertType ||
  367. .JP2 == self.convertType ||
  368. .BMP == self.convertType ||
  369. .TGA == self.convertType {
  370. moreLabelString = String(format: "%@ %@", KMLocalizedString("The first 10 pages for free"), KMLocalizedString("Unlimited Convert"))
  371. }
  372. }
  373. #endif
  374. if convertType.rawValue >= 7 && convertType.rawValue <= 14 {
  375. offset += imageDPISelectButton.frame.size.height
  376. imageDPISelectButton.isHidden = false
  377. buttonTopOffset.constant = 5
  378. } else {
  379. imageDPISelectButton.isHidden = true
  380. buttonTopOffset.constant = -26
  381. }
  382. if moreLabelString.count < 1 {
  383. offset += 5
  384. moreConvertBox.isHidden = true
  385. moreButton.isHidden = true
  386. } else {
  387. offset += (moreButton.frame.size.height + 5)
  388. moreConvertBox.isHidden = false
  389. moreButton.isHidden = false
  390. moreConvertLabel.stringValue = moreLabelString
  391. if let range = moreLabelString.range(of: NSLocalizedString("Unlimited Convert", comment: "")) {
  392. let newR: NSRange = moreLabelString.nsRange(from: range)!
  393. let attributedStr = NSMutableAttributedString(string: moreLabelString)
  394. attributedStr.addAttribute(.foregroundColor, value: NSColor.labelColor, range: NSRange(location: 0, length: newR.location - 1))
  395. attributedStr.addAttribute(.foregroundColor, value: NSColor(red: 8/255, green: 124/255, blue: 1, alpha: 1), range: newR)
  396. attributedStr.addAttribute(.underlineStyle, value: NSUnderlineStyle.single.rawValue, range: newR)
  397. moreConvertLabel.attributedStringValue = attributedStr
  398. }
  399. }
  400. if .Excel == convertType {
  401. separateStypeTopOffset.constant = separateStypeBox.frame.size.height + 58 + 16
  402. extractTableTopOffset.constant = separateStypeBox.frame.size.height + 50
  403. separateStypeBox.isHidden = true
  404. extractTableButton.isHidden = true
  405. excelStyleBox.isHidden = false
  406. separateStypeLabel.isHidden = false
  407. separateStypeLabel.stringValue = NSLocalizedString("Excel Worksheet Settings", comment: "")
  408. separateButton.title = NSLocalizedString("Convert each page to a separate worksheet", comment: "")
  409. singleButton.title = NSLocalizedString("Convert all pages to a single worksheet", comment: "")
  410. buttonClicked_extractTable(extractTableButton)
  411. } else if .AdvancedWord == convertType {
  412. singleButton.setTitleColor(NSColor.labelColor)
  413. separateButton.setTitleColor(NSColor.labelColor)
  414. separateStypeLabel.textColor = NSColor.labelColor
  415. separateButton.state = NSControl.StateValue.on
  416. singleButton.isEnabled = true
  417. separateButton.isEnabled = true
  418. isAllInOneSheet = false
  419. separateStypeTopOffset.constant = separateStypeBox.frame.size.height + 40
  420. extractTableButton.isHidden = true
  421. separateStypeBox.isHidden = false
  422. separateStypeLabel.isHidden = false
  423. separateStypeLabel.stringValue = NSLocalizedString("Layout Settings", comment: "")
  424. separateButton.title = NSLocalizedString("Retain Flowing Text", comment: "")
  425. singleButton.title = NSLocalizedString("Retain Page Layout", comment: "")
  426. } else if .CSV == convertType {
  427. separateStypeTopOffset.constant = extractTableButton.frame.size.height + 30
  428. extractTableTopOffset.constant = 12
  429. extractTableButton.isHidden = false
  430. separateStypeBox.isHidden = true
  431. separateStypeLabel.isHidden = true
  432. } else {
  433. separateStypeTopOffset.constant = 15
  434. separateStypeBox.isHidden = true
  435. extractTableButton.isHidden = true
  436. separateStypeLabel.isHidden = true
  437. }
  438. buttonBottemOffset.constant = offset
  439. }
  440. @IBAction func buttonClicked_extractTable(_ sender: NSButton) {
  441. if extractTableButton.state == .on {
  442. singleButton.setTitleColor(KMAppearance.Layout.b15_1Color())
  443. separateButton.setTitleColor(KMAppearance.Layout.b15_1Color())
  444. separateStypeLabel.textColor = KMAppearance.Layout.b15_1Color()
  445. singleButton.isEnabled = false
  446. separateButton.isEnabled = false
  447. separateButton.state = .off
  448. singleButton.state = .off
  449. } else {
  450. singleButton.setTitleColor(NSColor.labelColor)
  451. separateButton.setTitleColor(NSColor.labelColor)
  452. separateStypeLabel.textColor = NSColor.labelColor
  453. separateButton.state = .on
  454. singleButton.isEnabled = true
  455. separateButton.isEnabled = true
  456. isAllInOneSheet = false
  457. }
  458. }
  459. @IBAction func buttonClicked_Cancel(_ sender: NSButton) {
  460. if FileManager.default.fileExists(atPath: kConvertFileSavePath ?? "") {
  461. do {
  462. try FileManager.default.removeItem(atPath: kConvertFileSavePath ?? "")
  463. } catch {
  464. print("Error removing item at path: (error.localizedDescription)")
  465. }
  466. }
  467. dismissSheet(sender)
  468. }
  469. func dismissSheet(_ sender: NSButton) {
  470. // if #available(macOS 10.13, *) {
  471. // self.window?.endSheet(sender.window!)
  472. // } else {
  473. // NSApp.endSheet(self.window!)
  474. // }
  475. // self.window?.orderOut(self)
  476. self.km_quick_endSheet()
  477. }
  478. func showCriticalAlert(_ alertMsg: String?) {
  479. let alert = NSAlert()
  480. alert.alertStyle = .critical
  481. if let msg = alertMsg {
  482. alert.informativeText = msg
  483. } else {
  484. let st = self.pdfDocument?.documentURL.lastPathComponent.count ?? 0 > 0 ? self.pdfDocument?.documentURL.lastPathComponent : KMLocalizedString("Untitled.pdf", nil)
  485. alert.messageText = String(format: "%@ %@", st!, KMLocalizedString("Invalid page range or the page number is out of range. Please try again.", nil))
  486. }
  487. alert.runModal()
  488. }
  489. func produceNewPDF(with pagesArray: [CPDFPage]) {
  490. if tempPDFDocument != nil{
  491. tempPDFDocument = nil
  492. }
  493. tempPDFDocument = CPDFDocument()
  494. for i in 0..<(self.pdfDocument?.pageCount ?? 0) {
  495. tempPDFDocument?.removePage(at: i)
  496. }
  497. for addedPage in pagesArray {
  498. tempPDFDocument?.insertPageObject(addedPage, at: tempPDFDocument!.pageCount)
  499. }
  500. self.prePDFView.document = tempPDFDocument
  501. self.prePDFView.goToFirstPage(nil)
  502. self.currentPageIndexTextField.stringValue = "1"
  503. self.totalPageCountLabel.stringValue = " / \(tempPDFDocument!.pageCount)"
  504. }
  505. func pageRangeSetON(_ sender: NSButton) {
  506. allPageButton.state = .off
  507. oddPageButton.state = .off
  508. evenPageButton.state = .off
  509. handInputButton.state = .off
  510. currentPageButton.state = .off
  511. sender.state = .on
  512. if sender == handInputButton {
  513. pageRangeTextField.isEditable = true
  514. pageRangeTextField.isSelectable = true
  515. // self.pageRangeTextField.textColor = NSColor.textColor
  516. window?.makeFirstResponder(pageRangeTextField)
  517. } else {
  518. pageRangeTextField.isEditable = false
  519. pageRangeTextField.isSelectable = false
  520. // self.pageRangeTextField.textColor = NSColor.lightGrayColor
  521. window?.makeFirstResponder(self)
  522. }
  523. }
  524. @IBAction func buttonClicked_FormatSelect(_ sender: NSButton) {
  525. guard let item = self.formatSelectButton.selectedItem else { return }
  526. self.convertType = KMConvertType(rawValue: item.tag) ?? .Word
  527. updataView()
  528. }
  529. func transform(with string: String) {
  530. if string == KMLocalizedString("Create Sheet for each Table", nil) {
  531. self.excelWorksheetOption = .forEachTable
  532. } else if string == KMLocalizedString("Create Sheet for each Page", nil) {
  533. self.excelWorksheetOption = .forEachPage
  534. } else if string == KMLocalizedString("Create single Sheet for File", nil) {
  535. self.excelWorksheetOption = .forTheDocument
  536. }
  537. }
  538. @IBAction func buttonClicked_excelStyle(_ sender: NSButton) {
  539. if sender.isEqual(self.onlyTextBtn) {
  540. self.tableMenu.isEnabled = false
  541. self.allContentMenu.isEnabled = false
  542. self.excelContentOption = .onlyText
  543. self.excelWorksheetOption = .forEachTable
  544. } else if (sender.isEqual(self.onlyTableBtn)) {
  545. self.tableMenu.isEnabled = true
  546. self.allContentMenu.isEnabled = false
  547. self.excelContentOption = .onlyTable
  548. transform(with: self.tableMenu.selectedItem?.title ?? "")
  549. } else if (sender.isEqual(self.allContentBtn)) {
  550. self.tableMenu.isEnabled = false
  551. self.allContentMenu.isEnabled = true
  552. self.excelContentOption = .allContent
  553. transform(with: self.allContentMenu.selectedItem?.title ?? "")
  554. }
  555. }
  556. @IBAction func buttonClicked_tableMenu(_ sender: NSButton) {
  557. transform(with: self.tableMenu.selectedItem?.title ?? "")
  558. }
  559. @IBAction func buttonClicked_allContentMenu(_ sender: NSButton) {
  560. transform(with: self.allContentMenu.selectedItem?.title ?? "")
  561. }
  562. @IBAction func buttonClicked_PageSelect(_ sender: NSButton) {
  563. pageRangeSetON(sender)
  564. self.lockPassword = ""
  565. let pagesArray = NSMutableArray()
  566. for i in 0..<(self.pdfDocument?.pageCount ?? 0) {
  567. let copyPage = self.pdfDocument?.page(at: i)
  568. pagesArray.add(copyPage!)
  569. }
  570. if sender.isEqual(self.oddPageButton) {
  571. pagesArray.subArray(type: .Odd)
  572. } else if (sender.isEqual(self.evenPageButton)) {
  573. pagesArray.subArray(type: .Even)
  574. } else if (sender.isEqual(self.currentPageButton)) {
  575. pagesArray.removeAllObjects()
  576. let page = self.prePDFView.currentPage()
  577. if (page != nil) {
  578. pagesArray.add(page as Any)
  579. }
  580. }
  581. produceNewPDF(with: pagesArray as! [CPDFPage])
  582. // perform(#selector(produceNewPDF(with:)), with: pagesArray, afterDelay: 2)
  583. // performSelector(produceNewPDF(with:), withObject: pagesArray, afterDelay: 2)
  584. }
  585. @IBAction func buttonClicked_DpiSelect(_ sender: NSPopUpButton) {
  586. let index = sender.indexOfSelectedItem
  587. var dpi = 0
  588. if index == 0 {
  589. dpi = 50
  590. } else if index == 1 {
  591. dpi = 72
  592. } else if index == 2 {
  593. dpi = 96
  594. } else if index == 3 {
  595. dpi = 150
  596. } else if index == 4 {
  597. dpi = 300
  598. } else if index == 5 {
  599. dpi = 600
  600. }
  601. self.imageDPINumber = dpi
  602. }
  603. @IBAction func buttonClick_PreviousPage(_ sender: NSButton) {
  604. if self.prePDFView.canGoToPreviousPage() {
  605. self.prePDFView.goToPreviousPage(nil)
  606. let currentIndex = self.prePDFView.document?.index(for: self.prePDFView.currentPage()) ?? 0
  607. self.currentPageIndexTextField.stringValue = "\(currentIndex + 1)"
  608. }
  609. }
  610. @IBAction func buttonClicked_NextPage(_ sender: NSButton) {
  611. if self.prePDFView.canGoToNextPage() {
  612. self.prePDFView.goToNextPage(nil)
  613. let currentIndex = self.prePDFView.document?.index(for: self.prePDFView.currentPage())
  614. self.currentPageIndexTextField.stringValue = "\((currentIndex ?? 0) + 1)"
  615. }
  616. }
  617. @IBAction func buttonClicked_Batch(_ sender: NSButton) {
  618. if !IAPProductsManager.default().isAvailableAllFunction() {
  619. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  620. return
  621. }
  622. if self.pdfDocument?.documentURL == nil {
  623. NSSound.beep()
  624. return
  625. }
  626. if self.callBackBlock != nil {
  627. self.callBackBlock!()
  628. self.callBackBlock = nil
  629. }
  630. dismissSheet(sender)
  631. }
  632. @IBAction func buttonClicked_Convert(_ sender: Any) {
  633. self.window?.makeFirstResponder(self.prePDFView)
  634. if self.handInputButton.state == .on {
  635. let fileAttribute = KMFileAttribute()
  636. fileAttribute.pdfDocument = self.pdfDocument
  637. fileAttribute.filePath = self.pdfDocument?.documentURL.path ?? ""
  638. fileAttribute.bAllPage = false
  639. if self.handInputButton.state == .on {
  640. fileAttribute.pagesType = .custom
  641. }
  642. fileAttribute.pagesString = self.pageRangeTextField.stringValue
  643. if fileAttribute.fetchSelectPages().isEmpty {
  644. return
  645. }
  646. }
  647. let openPanel = NSOpenPanel()
  648. openPanel.canChooseFiles = false
  649. openPanel.canChooseDirectories = true
  650. openPanel.canCreateDirectories = true
  651. openPanel.beginSheetModal(for: self.window!) { result in
  652. if result == .OK {
  653. self.savePath = openPanel.url!.path
  654. self.beginConvert()
  655. }
  656. }
  657. }
  658. func beginConvert() {
  659. var isLimitConvert = false
  660. #if VERSION_FREE
  661. #if VERSION_DMG
  662. // 桌机版
  663. if IAPProductsManager.default().isAvailableAllFunction() {
  664. if IAPProductsManager.default().isAvailableAdvancedPDFToOffice() {
  665. isLimitConvert = false
  666. } else {
  667. if (.PNG == self.convertType ||
  668. .JPEG == self.convertType ||
  669. .JPG == self.convertType ||
  670. .HTML == self.convertType ||
  671. .Text == self.convertType ||
  672. .Word == self.convertType) {
  673. isLimitConvert = false
  674. } else {
  675. isLimitConvert = true
  676. }
  677. }
  678. } else {
  679. isLimitConvert = true
  680. }
  681. #else
  682. // 免费版
  683. if IAPProductsManager.default().isAvailableAdvancedPDFToOffice() == false {
  684. isLimitConvert = true
  685. }
  686. #endif
  687. #else
  688. // 付费版
  689. if IAPProductsManager.default().isAvailableAdvancedPDFToOffice() {
  690. isLimitConvert = false
  691. } else {
  692. if (.PNG == self.convertType ||
  693. .JPEG == self.convertType ||
  694. .JPG == self.convertType ||
  695. .HTML == self.convertType ||
  696. .Text == self.convertType ||
  697. .Word == self.convertType) {
  698. isLimitConvert = false
  699. } else {
  700. isLimitConvert = true
  701. }
  702. }
  703. #endif
  704. self.showWaitting()
  705. let pages = NSMutableArray()
  706. DispatchQueue.global(qos: .background).async { [self] in
  707. let filePath = getConvertFileSavePath()
  708. if (FileManager.default.fileExists(atPath: filePath)) {
  709. try?FileManager.default.removeItem(atPath: filePath)
  710. }
  711. if self.prePDFView.document.write(toFile: filePath) {
  712. for i in 0..<self.prePDFView.document.pageCount {
  713. pages.add(i + 1)
  714. }
  715. }
  716. DispatchQueue.main.async {
  717. if pages.count < 1 {
  718. self.hideWaitting()
  719. let alert = NSAlert()
  720. alert.alertStyle = .critical
  721. 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: ""))"
  722. alert.runModal()
  723. return
  724. }
  725. let pageCount = pages.count
  726. var selectPages = [Int]()
  727. if isLimitConvert {
  728. if pageCount >= 10 {
  729. for i in 0..<10 {
  730. selectPages.append(pages[i] as! Int)
  731. }
  732. } else {
  733. selectPages = pages as! [Int]
  734. }
  735. } else {
  736. selectPages = pages as! [Int]
  737. }
  738. let convert = KMPDFConvert()
  739. convert.filePath = filePath
  740. convert.pages = selectPages
  741. convert.isAllInOneSheet = self.isAllInOneSheet
  742. if self.convertType == .Word {
  743. convert.type = 0
  744. } else {
  745. convert.type = 1
  746. }
  747. convert.isExtractTable = self.extractTableButton.state == .on
  748. convert.outputFolderPath = self.savePath
  749. convert.outputFileName = (self.pdfDocument?.documentURL.deletingPathExtension().lastPathComponent) ?? NSLocalizedString("Untitled", comment: "")
  750. if self.convertType == .AdvancedWord {
  751. convert.convertType = .word
  752. } else if self.convertType == .JPEG ||
  753. self.convertType == .JPG ||
  754. self.convertType == .PNG ||
  755. self.convertType == .GIF ||
  756. self.convertType == .TIFF ||
  757. self.convertType == .TGA ||
  758. self.convertType == .BMP ||
  759. self.convertType == .JP2 {
  760. convert.convertType = KMPDFConvertType(rawValue: self.convertType.rawValue) ?? .word
  761. convert.options = [KMPDFConvertOptionsKeyImageDPI : self.imageDPINumber,
  762. KMPDFConvertOptionsKeyImageWithAnnotation : true] as [String : Any]
  763. } else {
  764. convert.convertType = KMPDFConvertType(rawValue: self.convertType.rawValue) ?? .word
  765. }
  766. if self.convertType == .Excel {
  767. convert.excelContentOption = self.excelContentOption
  768. convert.excelWorksheetOption = self.excelWorksheetOption
  769. }
  770. convert.password = self.lockPassword
  771. KMPDFConvertManager.defaultManager.convert(convert: convert) { [self] (finished, error) in
  772. self.hideWaitting()
  773. if finished {
  774. self.buttonClicked_Cancel(cancelButton)
  775. if FileManager.default.fileExists(atPath: convert.outputFilePath) {
  776. let workspace = NSWorkspace.shared
  777. let url = URL(fileURLWithPath: convert.outputFilePath)
  778. workspace.activateFileViewerSelecting([url])
  779. }
  780. } else if let error = error {
  781. let err: NSError = error as NSError
  782. var erroeString = ""
  783. switch err.code {
  784. case CPDFConverterEncryptError:
  785. erroeString = NSLocalizedString("Password required or incorrect password. Please re-enter your password and try again", comment: "")
  786. break
  787. case CPDFConverterPermissionError:
  788. erroeString = NSLocalizedString("The license doesn't allow the permission", comment: "")
  789. break
  790. case CPDFConverterMallocError:
  791. erroeString = NSLocalizedString("Malloc failure", comment: "")
  792. break
  793. case CPDFConverterUnknownError:
  794. erroeString = NSLocalizedString("Unknown error in processing conversion. Please try again later", comment: "")
  795. break
  796. case CPDFConverterPDFUnknownError:
  797. erroeString = NSLocalizedString("Unknown error in processing PDF. Please try again later", comment: "")
  798. break
  799. case CPDFConverterPDFFileError:
  800. erroeString = NSLocalizedString("File not found or could not be opened. Check if your file exists or choose another file to convert", comment: "")
  801. break
  802. case CPDFConverterPDFFormatError:
  803. erroeString = NSLocalizedString("File not in PDF format or corruptead. Change a PDF file and try again", comment: "")
  804. break
  805. case CPDFConverterPDFSecurityError:
  806. erroeString = NSLocalizedString("Unsupported security scheme", comment: "")
  807. break
  808. case CPDFConverterPDFPageError:
  809. erroeString = NSLocalizedString("Page not found or content error", comment: "")
  810. break
  811. default:
  812. erroeString = NSLocalizedString("Table not found", comment: "")
  813. break
  814. }
  815. let alert = NSAlert()
  816. alert.alertStyle = .critical
  817. alert.messageText = NSLocalizedString("Conversion Failed", comment: "")
  818. alert.informativeText = erroeString
  819. alert.addButton(withTitle: NSLocalizedString("OK", comment: ""))
  820. if #available(OSX 10.14, *) {
  821. alert.beginSheetModal(for: self.window!, completionHandler: nil)
  822. } else {
  823. alert.runModal()
  824. }
  825. }
  826. }
  827. }
  828. }
  829. }
  830. func getConvertFileSavePath() -> String {
  831. var path = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.applicationSupportDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).last
  832. path?.append("/")
  833. path?.append(Bundle.main.bundleIdentifier!)
  834. if (FileManager.default.fileExists(atPath: path!) == false) {
  835. try?FileManager.default.createDirectory(atPath: path!, withIntermediateDirectories: false)
  836. }
  837. path?.append("/")
  838. path?.append("convert.pdf")
  839. return path!
  840. }
  841. @IBAction func buttonClicked_MoreConvert(_ sender: Any) {
  842. #if VERSION_DMG
  843. if IAPProductsManager.default().isAvailableAllFunction() && !IAPProductsManager.default().isAvailableAdvancedPDFToOffice() {
  844. let limitWC = KMPurchaseLimitWindowController.currentLimitWC()
  845. limitWC.continueBlock = { windowController in
  846. }
  847. limitWC.window?.center()
  848. limitWC.showWindow(nil)
  849. } else {
  850. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  851. }
  852. #else
  853. if IAPProductsManager.default().isAvailableAllFunction() {
  854. var vc: KMToolCompareWindowController? = nil
  855. if convertType == .Word || convertType == .AdvancedWord {
  856. // vc = KMToolCompareWindowController(toolType: .Convert, selectNum: 1)
  857. vc = KMToolCompareWindowController.toolCompare(toolType: .Convert, selectNum: 1)
  858. } else if convertType == .Excel {
  859. // vc = KMToolCompareWindowController(toolType: .Convert, selectNum: 2)
  860. vc = KMToolCompareWindowController.toolCompare(toolType: .Convert, selectNum: 2)
  861. } else if convertType == .PPT {
  862. // vc = KMToolCompareWindowController(toolType: .Convert, selectNum: 3)
  863. vc = KMToolCompareWindowController.toolCompare(toolType: .Convert, selectNum: 3)
  864. } else if convertType.rawValue < 15 && convertType.rawValue > 7 {
  865. // vc = KMToolCompareWindowController(toolType: .Convert, selectNum: 4)
  866. vc = KMToolCompareWindowController.toolCompare(toolType: .Convert, selectNum: 4)
  867. } else {
  868. // vc = KMToolCompareWindowController(toolType: .Convert, selectNum: 0)
  869. vc = KMToolCompareWindowController.toolCompare(toolType: .Convert, selectNum: 0)
  870. }
  871. vc?.showWindow(nil)
  872. } else {
  873. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  874. }
  875. #endif
  876. self.buttonClicked_Cancel(self.cancelButton)
  877. }
  878. @IBAction func buttonItemClick_SepSingle(_ sender: Any) {
  879. if .on == self.singleButton.state {
  880. self.isAllInOneSheet = true
  881. } else {
  882. self.isAllInOneSheet = false
  883. }
  884. }
  885. func controlTextDidEndEditing(_ obj: Notification) {
  886. let object = obj.object
  887. if (object as AnyObject).isEqual(self.currentPageIndexTextField) == true {
  888. let num: Int = Int(self.currentPageIndexTextField.stringValue) ?? 1
  889. let targetPage = self.prePDFView.document.page(at: UInt(num - 1))
  890. self.prePDFView.go(to: targetPage)
  891. } else if (object as AnyObject).isEqual(self.pageRangeTextField) == true {
  892. guard self.handInputButton.state == .on else { return }
  893. let fileAttribute = KMFileAttribute()
  894. fileAttribute.pdfDocument = self.pdfDocument
  895. fileAttribute.bAllPage = false
  896. fileAttribute.pagesType = .custom
  897. fileAttribute.pagesString = self.pageRangeTextField.stringValue
  898. if fileAttribute.fetchSelectPages().count > 0 {
  899. let pagesArray = NSMutableArray()
  900. for pageNum in fileAttribute.fetchSelectPages() {
  901. let tpage = self.pdfDocument?.page(at: UInt(pageNum - 1))
  902. pagesArray.add(tpage as Any)
  903. }
  904. self.produceNewPDF(with: pagesArray as! [CPDFPage])
  905. } else {
  906. self.showCriticalAlert(nil)
  907. }
  908. }
  909. }
  910. func controlTextDidChange(_ obj: Notification) {
  911. if let textField = obj.object as? NSTextField {
  912. if textField.isEqual(self.currentPageIndexTextField) {
  913. if let stringValue = self.currentPageIndexTextField.formatter?.string(for: NSNumber(value: Float(self.currentPageIndexTextField.stringValue) ?? 0)) {
  914. if let integerValue = Int(stringValue) {
  915. var string = stringValue
  916. if integerValue > self.prePDFView.document.pageCount {
  917. string = "(self.prePDFView.document.pageCount)"
  918. } else if integerValue <= 0 {
  919. string = "1"
  920. }
  921. self.currentPageIndexTextField.stringValue = string
  922. }
  923. }
  924. }
  925. }
  926. }
  927. }
  928. @objc enum KMSubArrayType: Int {
  929. case Odd = 0
  930. case Even
  931. }
  932. extension NSMutableArray{
  933. func subArray(type: KMSubArrayType) {
  934. if self.count == 0 { return }
  935. if type.rawValue > 1 || type.rawValue < 0 { return }
  936. let newArray = NSMutableArray()
  937. for i in 0..<self.count {
  938. if i % 2 == type.rawValue {
  939. newArray.add(self[i])
  940. }
  941. }
  942. self.removeAllObjects()
  943. self.addObjects(from: newArray as! [Any])
  944. }
  945. }