KMConvertWindowController.swift 60 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418
  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, NSComboBoxDelegate{
  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 pageRangeBox: NSComboBox!
  29. @IBOutlet var convertButton: NSButton!
  30. @IBOutlet var cancelButton: NSButton!
  31. @IBOutlet var batchButton: NSButton!
  32. @IBOutlet var upgradeButton: NSButton!
  33. @IBOutlet var separateStypeTopOffset: NSLayoutConstraint!
  34. @IBOutlet var separateButton: NSButton!
  35. @IBOutlet var singleButton: NSButton!
  36. @IBOutlet var separateStypeBox: NSBox!
  37. @IBOutlet var extractTableButton: NSButton!
  38. @IBOutlet var extractTableTopOffset: NSLayoutConstraint!
  39. @IBOutlet var separateStypeLabel: NSTextField!
  40. @IBOutlet var excelStyleBox: NSBox!
  41. @IBOutlet var onlyTextBtn: NSButton!
  42. @IBOutlet var onlyTableBtn: NSButton!
  43. @IBOutlet var allContentBtn: NSButton!
  44. @IBOutlet var tableMenu1: NSMenuItem!
  45. @IBOutlet var tableMenu2: NSMenuItem!
  46. @IBOutlet var tableMenu3: NSMenuItem!
  47. @IBOutlet var allContentMenu2: NSMenuItem!
  48. @IBOutlet var allContentMenu3: NSMenuItem!
  49. @IBOutlet var tableMenu: NSPopUpButton!
  50. @IBOutlet var allContentMenu: NSPopUpButton!
  51. @IBOutlet var ocrBox: NSBox!
  52. @IBOutlet var ocrLabel: NSTextField!
  53. @IBOutlet var ocrButton: NSButton!
  54. @IBOutlet var ocrLanguageBox: NSPopUpButton!
  55. @IBOutlet var ocrTopOffset: NSLayoutConstraint!
  56. var isAllInOneSheet = false
  57. var modalSession: NSApplication.ModalSession?
  58. var pdfDocument: CPDFDocument?
  59. var maskView: KMBookletMaskView?
  60. var convertType: KMConvertType = .Word
  61. var imageDPINumber: Int = 0
  62. var callBackBlock: convertBatchCallBack?
  63. var currentPage: CPDFPage?
  64. var savePath: String = ""
  65. var lockPassword: String = ""
  66. var tempPDFDocument: CPDFDocument?
  67. var excelContentOption: CPDFConvertExcelContentOptions?
  68. var excelWorksheetOption: CPDFConvertExcelWorksheetOptions?
  69. private var fileAttri_: KMFileAttribute?
  70. private var ocrLanguage_: COCRLanguage = .english
  71. deinit {
  72. #if DEBUG
  73. NSLog("====KMConvertWindowController==deinit")
  74. #endif
  75. }
  76. convenience init(documemtV:CPDFDocument, currentPage:CPDFPage, convertT:KMConvertType, handle:@escaping convertBatchCallBack) {
  77. self.init(windowNibName: "KMConvertWindowController")
  78. if (documemtV.documentURL != nil) {
  79. let pageIndex = documemtV.index(for: currentPage)
  80. self.pdfDocument = CPDFDocument(url: documemtV.documentURL)
  81. let isLoc: Bool = self.pdfDocument!.isLocked
  82. if (!documemtV.isLocked && isLoc) {
  83. self.lockPassword = documemtV.password
  84. self.pdfDocument?.unlock(withPassword: self.lockPassword)
  85. }
  86. self.currentPage = self.pdfDocument?.page(at: pageIndex )
  87. } else {
  88. self.pdfDocument = documemtV
  89. self.currentPage = currentPage
  90. }
  91. self.callBackBlock = handle
  92. if convertT.rawValue > 15 || convertT.rawValue < 0 {
  93. self.convertType = .Word
  94. } else {
  95. self.convertType = convertT
  96. }
  97. }
  98. convenience init(localPath:String, handle:@escaping convertBatchCallBack) {
  99. self.init(windowNibName: "KMConvertWindowController")
  100. self.pdfDocument = CPDFDocument(url: URL(fileURLWithPath: localPath))
  101. self.callBackBlock = handle
  102. let isLoc: Bool = self.pdfDocument!.isLocked
  103. if (isLoc) {
  104. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.5) {
  105. let url = self.pdfDocument?.documentURL
  106. KMBaseWindowController.checkPassword(url: url!, type: .owner) { [weak self] success, resultPassword in
  107. if success {
  108. self?.lockPassword = resultPassword
  109. self?.pdfDocument?.unlock(withPassword: resultPassword)
  110. self?.currentPage = self?.pdfDocument?.page(at: 0)
  111. self?.convertType = .Word
  112. }
  113. }
  114. }
  115. }
  116. }
  117. override func windowDidLoad() {
  118. super.windowDidLoad()
  119. let preView: CPDFView = CPDFView(frame: self.prePdfBGView.bounds)
  120. self.prePdfBGView.addSubview(preView)
  121. self.prePDFView = preView
  122. self.ocrBox.fillColor = .gridColor
  123. localizedLanguage()
  124. self.currentPageIndexTextField.delegate = self;
  125. pageRangLabel.stringValue = NSLocalizedString("Page Range:", comment: "")
  126. pageRangeBox.addItem(withObjectValue: NSLocalizedString("All Pages", comment: ""))
  127. pageRangeBox.addItem(withObjectValue: NSLocalizedString("Current Page", comment: ""))
  128. pageRangeBox.addItem(withObjectValue: NSLocalizedString("Odd Pages Only", comment: ""))
  129. pageRangeBox.addItem(withObjectValue: NSLocalizedString("Even Pages Only", comment: ""))
  130. pageRangeBox.addItem(withObjectValue: NSLocalizedString("e.g. 1,3-5,10", comment: ""))
  131. (pageRangeBox.cell as? NSComboBoxCell)?.placeholderString = NSLocalizedString("e.g. 1,3-5,10", comment: "")
  132. pageRangeBox.selectItem(at: 0)
  133. pageRangeBox.isEditable = false
  134. ocrLanguageBox.selectItem(at: 2)
  135. ocrLabel.textColor = KMAppearance.Layout.h2Color()
  136. ocrLanguageBox.isEnabled = false
  137. ocrButton.state = .off
  138. let isLoc: Bool = self.pdfDocument!.isLocked
  139. if (isLoc) {
  140. self.showWaitting()
  141. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
  142. let url = URL(fileURLWithPath: self.pdfDocument!.documentURL.path)
  143. KMBaseWindowController.checkPassword(url: url, type: .owner) { result, password in
  144. self.hideWaitting()
  145. if password.count > 0 {
  146. let unlockSuccess: Bool = ((self.pdfDocument?.unlock(withPassword: password)) != nil)
  147. self.lockPassword = password
  148. if unlockSuccess {
  149. self.currentPage = self.pdfDocument?.page(at: 0)
  150. }
  151. self.configuView()
  152. } else {
  153. self.buttonClicked_Cancel(self.cancelButton)
  154. }
  155. }
  156. }
  157. } else {
  158. self.configuView()
  159. }
  160. if #available(macOS 10.14, *) {
  161. let appearanceName = NSApp.effectiveAppearance.bestMatch(from: [.aqua, .darkAqua])
  162. if appearanceName == .darkAqua {
  163. moreConvertLabel.textColor = NSColor.white
  164. }
  165. }
  166. isAllInOneSheet = false
  167. separateButton.state = .on
  168. singleButton.state = .off
  169. allContentBtn.state = .on
  170. allContentMenu.isEnabled = true
  171. tableMenu.isEnabled = false
  172. excelContentOption = .allContent
  173. excelWorksheetOption = .forEachPage
  174. NotificationCenter.default.addObserver(self, selector: #selector(PDFViewDocumentChangedNotification(notification:)), name: NSNotification.Name.CPDFViewPageChanged, object: nil)
  175. }
  176. @objc func PDFViewDocumentChangedNotification(notification: NSNotification) {
  177. let pageIndex = self.prePDFView.currentPageIndex+1
  178. self.currentPageIndexTextField.stringValue = "\(pageIndex)"
  179. }
  180. func windowShouldClose(_ sender: NSWindow) -> Bool {
  181. self.dismissSheet()
  182. return true
  183. }
  184. func localizedLanguage() {
  185. // formatLabel.stringValue = KMLocalizedString("Format:")
  186. // separateButton.title = KMLocalizedString("Convert each page to a separate worksheet")
  187. // singleButton.title = KMLocalizedString("Convert all pages to a single worksheet")
  188. // box.title = KMLocalizedString("Page Range:")
  189. // separateStypeLabel.stringValue = KMLocalizedString("Excel Worksheet Settings")
  190. // extractTableButton.title = KMLocalizedString("Extract Tables Only")
  191. // allPageButton.title = KMLocalizedString("All Pages")
  192. // currentPageButton.title = KMLocalizedString("Current Page")
  193. // oddPageButton.title = KMLocalizedString("Odd Pages Only")
  194. // evenPageButton.title = KMLocalizedString("Even Pages Only")
  195. //
  196. // pageRangeTextField.placeholderString = KMLocalizedString("e.g. 1,3-5,10")
  197. formatLabel.stringValue = NSLocalizedString("Format:", comment: "")
  198. separateButton.title = NSLocalizedString("Convert each page to a separate worksheet", comment: "")
  199. singleButton.title = NSLocalizedString("Convert all pages to a single worksheet", comment: "")
  200. ocrBox.title = NSLocalizedString("OCR Settings", comment: "")
  201. ocrLabel.stringValue = NSLocalizedString("Language Option", comment: "") + ":"
  202. ocrButton.title = NSLocalizedString("Recognize text", comment: "")
  203. separateStypeLabel.stringValue = NSLocalizedString("Excel Worksheet Settings", comment: "")
  204. extractTableButton.title = NSLocalizedString("Extract Tables Only", comment: "")
  205. batchButton.title = NSLocalizedString("Batch", comment: "")
  206. cancelButton.title = NSLocalizedString("Cancel", comment: "")
  207. convertButton.title = NSLocalizedString("Convert", comment: "")
  208. upgradeButton.title = NSLocalizedString("Upgrade", comment: "")
  209. onlyTextBtn.title = NSLocalizedString("Only Text", comment: "")
  210. onlyTableBtn.title = NSLocalizedString("Only Table", comment: "")
  211. allContentBtn.title = NSLocalizedString("All Content", comment: "")
  212. tableMenu1.title = NSLocalizedString("Create Sheet for each Table", comment: "")
  213. tableMenu2.title = NSLocalizedString("Create Sheet for each Page", comment: "")
  214. allContentMenu2.title = NSLocalizedString("Create Sheet for each Page", comment: "")
  215. tableMenu3.title = NSLocalizedString("Create single Sheet for File", comment: "")
  216. allContentMenu3.title = NSLocalizedString("Create single Sheet for File", comment: "")
  217. }
  218. func hideWaitting() {
  219. maskView?.removeFromSuperview()
  220. }
  221. func showWaitting() {
  222. if maskView == nil {
  223. maskView = KMBookletMaskView(frame: CGRect(x: 0, y: 0, width: self.window?.frame.size.width ?? 0, height: self.window?.frame.size.height ?? 0))
  224. }
  225. self.window?.contentView?.addSubview(maskView!)
  226. }
  227. func configuView() {
  228. self.prePDFView.autoScales = true
  229. self.prePDFView.wantsLayer = true
  230. self.prePDFView.document = self.pdfDocument
  231. self.imageDPISelectButton.removeAllItems()
  232. self.formatSelectButton.removeAllItems()
  233. let dpiArray = ["50 dpi", "72 dpi", "96 dpi", "150 dpi", "300 dpi", "600 dpi"]
  234. 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)","Json(.json)"]
  235. for (index, string) in formArray.enumerated() {
  236. let item = NSMenuItem()
  237. item.title = string
  238. item.target = self
  239. item.tag = index + 1
  240. self.formatSelectButton.menu?.addItem(item)
  241. }
  242. var isShowAdvanced = false
  243. let wordItem = NSMenuItem()
  244. wordItem.title = "Word (.docx)"
  245. wordItem.target = self
  246. var isShowUpgrade = false
  247. var convertSample: KMConvertType = .Word
  248. #if VERSION_FREE
  249. #if VERSION_DMG
  250. // 桌机版
  251. wordItem.tag = convertSample.rawValue
  252. isShowAdvanced = true
  253. if IAPProductsManager.default().isAvailableAllFunction() {
  254. if IAPProductsManager.default().isAvailableAdvancedPDFToOffice() {
  255. convertSample = .AdvancedWord
  256. wordItem.tag = convertSample.rawValue
  257. isShowAdvanced = false
  258. } else {
  259. isShowUpgrade = true
  260. }
  261. } else {
  262. isShowUpgrade = true
  263. }
  264. #else
  265. // 免费版
  266. convertSample = .Word
  267. wordItem.tag = convertSample.rawValue
  268. isShowAdvanced = true
  269. if IAPProductsManager.default().isAvailableAllFunction() {
  270. if IAPProductsManager.default().isAvailableAdvancedPDFToOffice() {
  271. convertSample = .AdvancedWord
  272. wordItem.tag = convertSample.rawValue
  273. isShowAdvanced = false
  274. } else {
  275. isShowUpgrade = true
  276. }
  277. } else {
  278. isShowUpgrade = true
  279. }
  280. #endif
  281. #else
  282. convertSample = .Word
  283. wordItem.tag = convertSample.rawValue
  284. // 付费版
  285. isShowAdvanced = true
  286. if IAPProductsManager.default().isAvailableAdvancedPDFToOffice() {
  287. isShowAdvanced = false
  288. convertSample = .AdvancedWord
  289. wordItem.tag = convertSample.rawValue
  290. } else {
  291. isShowUpgrade = true
  292. }
  293. #endif
  294. if wordItem.title != "" {
  295. if isShowAdvanced {
  296. let originStr = " \(KMLocalizedString("Standard")) "
  297. let str = KMLocalizedString("Word (.docx)")
  298. let attributedStr = NSMutableAttributedString(string: "\(str) \(originStr)")
  299. 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))
  300. attributedStr.addAttribute(NSAttributedString.Key.foregroundColor, value: NSColor.white, range: NSMakeRange(str.count + 2, originStr.count))
  301. let item = NSMenuItem()
  302. item.attributedTitle = attributedStr
  303. item.target = self
  304. item.tag = wordItem.tag
  305. self.formatSelectButton.menu?.insertItem(item, at: 0)
  306. } else {
  307. self.formatSelectButton.menu?.insertItem(wordItem, at: 0)
  308. }
  309. }
  310. if !isShowUpgrade {
  311. self.upgradeButton.isHidden = true
  312. }
  313. var selectIndex = 0
  314. if isShowAdvanced {
  315. let originStr = " \(NSLocalizedString("Advanced", comment: "")) "
  316. let str = NSLocalizedString("Word (.docx)", comment: "")
  317. let attributedStr = NSMutableAttributedString(string: "\(str) \(originStr)")
  318. 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))
  319. attributedStr.addAttribute(NSAttributedString.Key.foregroundColor, value: NSColor.white, range: NSMakeRange(str.count + 2, originStr.count))
  320. let item = NSMenuItem()
  321. item.attributedTitle = attributedStr
  322. item.target = self
  323. convertSample = .AdvancedWord
  324. item.tag = convertSample.rawValue
  325. self.formatSelectButton.menu?.insertItem(item, at: 0)
  326. }
  327. if self.convertType == .Word {
  328. selectIndex = 0
  329. } else {
  330. selectIndex = self.convertType.rawValue
  331. if isShowAdvanced {
  332. selectIndex += 1
  333. }
  334. if wordItem.title == "" {
  335. selectIndex -= 1
  336. }
  337. }
  338. self.formatSelectButton.selectItem(at: selectIndex)
  339. let item = self.formatSelectButton.selectedItem
  340. self.convertType = KMConvertType(rawValue: item?.tag ?? 0) ?? .Word
  341. self.imageDPISelectButton.isHidden = true
  342. self.buttonTopOffset.constant = -26
  343. self.imageDPISelectButton.addItems(withTitles: dpiArray)
  344. self.imageDPISelectButton.selectItem(at: 3)
  345. self.imageDPINumber = 150
  346. self.totalPageCountLabel.stringValue = " / \(self.pdfDocument?.pageCount ?? 1)"
  347. self.totalPageCountLabel.textColor = KMAppearance.Layout.h2Color()
  348. self.updataView()
  349. self.prePDFView.go(to: currentPage)
  350. let pageIndex = self.prePDFView.currentPageIndex+1
  351. self.currentPageIndexTextField.stringValue = "\(pageIndex)"
  352. if let documentURL = self.pdfDocument?.documentURL{
  353. self.pdfDocument = CPDFDocument(url: documentURL)
  354. if !lockPassword.isEmpty && lockPassword.count > 0{
  355. self.pdfDocument?.unlock(withPassword: lockPassword)
  356. }
  357. self.prePDFView.document = self.pdfDocument
  358. self.fileAttri_ = KMFileAttribute()
  359. self.fileAttri_?.filePath = documentURL.path
  360. }
  361. self.prePDFView.setDisplay(.singlePage)
  362. self.prePDFView.layoutDocumentView()
  363. }
  364. func updataView() {
  365. var moreLabelString: String = ""
  366. var offset: CGFloat = 0
  367. excelStyleBox.isHidden = true
  368. #if VERSION_FREE
  369. // 座机版
  370. if !IAPProductsManager.default().isAvailableAllFunction() {
  371. moreLabelString = String(format: "%@ %@", KMLocalizedString("The first 10 pages for free"), KMLocalizedString("Unlimited Convert"))
  372. } else {
  373. if !IAPProductsManager.default().isAvailableAdvancedPDFToOffice() {
  374. if .Word == self.convertType ||
  375. self.convertType == .AdvancedWord ||
  376. .Excel == self.convertType ||
  377. .PPT == self.convertType ||
  378. .CSV == self.convertType ||
  379. .RTF == self.convertType ||
  380. .GIF == self.convertType ||
  381. .TIFF == self.convertType ||
  382. .JP2 == self.convertType ||
  383. .BMP == self.convertType ||
  384. .TGA == self.convertType ||
  385. .Json == self.convertType {
  386. moreLabelString = String(format: "%@ %@", KMLocalizedString("The first 10 pages for free"), KMLocalizedString("Unlimited Convert"))
  387. }
  388. }
  389. }
  390. #else
  391. // 付费版
  392. if !(IAPProductsManager.default().isAvailableAdvancedPDFToOffice()) {
  393. if .Word == self.convertType ||
  394. self.convertType == .AdvancedWord ||
  395. .Excel == self.convertType ||
  396. .PPT == self.convertType ||
  397. .CSV == self.convertType ||
  398. .RTF == self.convertType ||
  399. .GIF == self.convertType ||
  400. .TIFF == self.convertType ||
  401. .JP2 == self.convertType ||
  402. .BMP == self.convertType ||
  403. .TGA == self.convertType ||
  404. .Json == self.convertType {
  405. moreLabelString = String(format: "%@ %@", KMLocalizedString("The first 10 pages for free"), KMLocalizedString("Unlimited Convert"))
  406. }
  407. }
  408. #endif
  409. if convertType.rawValue >= 7 && convertType.rawValue <= 14 {
  410. offset += imageDPISelectButton.frame.size.height
  411. imageDPISelectButton.isHidden = false
  412. buttonTopOffset.constant = 5
  413. } else {
  414. imageDPISelectButton.isHidden = true
  415. buttonTopOffset.constant = -26
  416. }
  417. if moreLabelString.count < 1 {
  418. offset += 5
  419. moreConvertBox.isHidden = true
  420. moreButton.isHidden = true
  421. } else {
  422. offset += (moreButton.frame.size.height + 5)
  423. moreConvertBox.isHidden = false
  424. moreButton.isHidden = false
  425. moreConvertLabel.stringValue = moreLabelString
  426. if let range = moreLabelString.range(of: NSLocalizedString("Unlimited Convert", comment: "")) {
  427. let newR: NSRange = moreLabelString.nsRange(from: range)!
  428. let attributedStr = NSMutableAttributedString(string: moreLabelString)
  429. attributedStr.addAttribute(.foregroundColor, value: NSColor.labelColor, range: NSRange(location: 0, length: newR.location - 1))
  430. attributedStr.addAttribute(.foregroundColor, value: NSColor(red: 8/255, green: 124/255, blue: 1, alpha: 1), range: newR)
  431. attributedStr.addAttribute(.underlineStyle, value: NSUnderlineStyle.single.rawValue, range: newR)
  432. moreConvertLabel.attributedStringValue = attributedStr
  433. }
  434. }
  435. if .Excel == convertType {
  436. separateStypeTopOffset.constant = separateStypeBox.frame.size.height + ocrBox.frame.size.height + 16 + 58
  437. extractTableTopOffset.constant = separateStypeBox.frame.size.height + 50
  438. ocrTopOffset.constant = 128
  439. separateStypeBox.isHidden = true
  440. extractTableButton.isHidden = true
  441. excelStyleBox.isHidden = false
  442. separateStypeLabel.isHidden = false
  443. ocrBox.isHidden = false
  444. separateStypeLabel.stringValue = NSLocalizedString("Excel Worksheet Settings", comment: "")
  445. separateButton.title = NSLocalizedString("Convert each page to a separate worksheet", comment: "")
  446. singleButton.title = NSLocalizedString("Convert all pages to a single worksheet", comment: "")
  447. buttonClicked_extractTable(extractTableButton)
  448. } else if .AdvancedWord == convertType {
  449. singleButton.setTitleColor(NSColor.labelColor)
  450. separateButton.setTitleColor(NSColor.labelColor)
  451. separateStypeLabel.textColor = NSColor.labelColor
  452. separateButton.state = NSControl.StateValue.on
  453. singleButton.isEnabled = true
  454. separateButton.isEnabled = true
  455. isAllInOneSheet = false
  456. separateStypeTopOffset.constant = separateStypeBox.frame.size.height + 40 + ocrBox.frame.size.height
  457. ocrTopOffset.constant = separateStypeBox.frame.size.height + 40
  458. extractTableButton.isHidden = true
  459. separateStypeBox.isHidden = false
  460. separateStypeLabel.isHidden = false
  461. separateStypeLabel.stringValue = NSLocalizedString("Layout Settings", comment: "")
  462. separateButton.title = NSLocalizedString("Retain Flowing Text", comment: "")
  463. singleButton.title = NSLocalizedString("Retain Page Layout", comment: "")
  464. ocrBox.isHidden = false
  465. } else if .Json == convertType {
  466. singleButton.setTitleColor(NSColor.labelColor)
  467. separateButton.setTitleColor(NSColor.labelColor)
  468. separateStypeLabel.textColor = NSColor.labelColor
  469. separateButton.state = NSControl.StateValue.on
  470. singleButton.isEnabled = true
  471. separateButton.isEnabled = true
  472. isAllInOneSheet = false
  473. separateStypeTopOffset.constant = separateStypeBox.frame.size.height + 40 + ocrBox.frame.size.height
  474. ocrTopOffset.constant = separateStypeBox.frame.size.height + 40
  475. extractTableButton.isHidden = true
  476. separateStypeBox.isHidden = false
  477. separateStypeLabel.isHidden = false
  478. separateStypeLabel.stringValue = NSLocalizedString("Json Worksheet Settings", comment: "")
  479. separateButton.title = NSLocalizedString("Extract text content", comment: "")
  480. singleButton.title = NSLocalizedString("Extract tables", comment: "")
  481. ocrBox.isHidden = false
  482. } else if .CSV == convertType {
  483. separateStypeTopOffset.constant = extractTableButton.frame.size.height + 30
  484. extractTableTopOffset.constant = 12
  485. extractTableButton.isHidden = false
  486. separateStypeBox.isHidden = true
  487. separateStypeLabel.isHidden = true
  488. ocrBox.isHidden = true
  489. } else if (.PPT == convertType || .RTF == convertType) {
  490. separateStypeTopOffset.constant = ocrBox.frame.size.height + 10
  491. ocrTopOffset.constant = 10
  492. separateStypeBox.isHidden = true
  493. extractTableButton.isHidden = true
  494. separateStypeLabel.isHidden = true
  495. ocrBox.isHidden = false
  496. } else if (.HTML == convertType ||
  497. .Text == convertType) {
  498. separateStypeTopOffset.constant = ocrBox.frame.size.height + 10
  499. ocrTopOffset.constant = 10
  500. separateStypeBox.isHidden = true
  501. extractTableButton.isHidden = true
  502. separateStypeLabel.isHidden = true
  503. ocrBox.isHidden = false
  504. } else {
  505. separateStypeTopOffset.constant = 10
  506. separateStypeBox.isHidden = true
  507. extractTableButton.isHidden = true
  508. separateStypeLabel.isHidden = true
  509. ocrBox.isHidden = true
  510. }
  511. buttonBottemOffset.constant = offset
  512. }
  513. @IBAction func buttonClicked_extractTable(_ sender: NSButton) {
  514. if extractTableButton.state == .on {
  515. singleButton.setTitleColor(KMAppearance.Layout.b15_1Color())
  516. separateButton.setTitleColor(KMAppearance.Layout.b15_1Color())
  517. separateStypeLabel.textColor = KMAppearance.Layout.b15_1Color()
  518. singleButton.isEnabled = false
  519. separateButton.isEnabled = false
  520. separateButton.state = .off
  521. singleButton.state = .off
  522. } else {
  523. singleButton.setTitleColor(NSColor.labelColor)
  524. separateButton.setTitleColor(NSColor.labelColor)
  525. separateStypeLabel.textColor = NSColor.labelColor
  526. separateButton.state = .on
  527. singleButton.isEnabled = true
  528. separateButton.isEnabled = true
  529. isAllInOneSheet = false
  530. }
  531. }
  532. @IBAction func buttonClicked_Cancel(_ sender: NSButton) {
  533. dismissSheet()
  534. }
  535. func dismissSheet() {
  536. if FileManager.default.fileExists(atPath: kConvertFileSavePath ?? "") {
  537. do {
  538. try FileManager.default.removeItem(atPath: kConvertFileSavePath ?? "")
  539. } catch {
  540. print("Error removing item at path: (error.localizedDescription)")
  541. }
  542. }
  543. // if self.prePDFView.document != nil {
  544. // self.prePDFView.document = nil
  545. // }
  546. // if self.tempPDFDocument != nil {
  547. // self.tempPDFDocument = nil
  548. // }
  549. self.km_quick_endSheet()
  550. }
  551. func showCriticalAlert(_ alertMsg: String?) {
  552. let alert = NSAlert()
  553. alert.alertStyle = .critical
  554. if let msg = alertMsg {
  555. alert.informativeText = msg
  556. } else {
  557. let st = self.pdfDocument?.documentURL.lastPathComponent.count ?? 0 > 0 ? self.pdfDocument?.documentURL.lastPathComponent : KMLocalizedString("Untitled.pdf")
  558. alert.messageText = String(format: "%@ %@", st!, KMLocalizedString("Invalid page range or the page number is out of range. Please try again."))
  559. }
  560. alert.runModal()
  561. }
  562. func produceNewPDF(with pagesArray: [CPDFPage]) {
  563. tempPDFDocument = nil
  564. // if self.tempPDFDocument == nil || self.tempPDFDocument!.isLocked {
  565. self.tempPDFDocument = CPDFDocument()
  566. // }
  567. var indexs = IndexSet()
  568. let pageCount = self.pdfDocument?.pageCount ?? 0
  569. for addedPage in pagesArray {
  570. // tempPDFDocument?.insertPageObject(addedPage, at: tempPDFDocument!.pageCount)
  571. let idx = addedPage.pageIndex()
  572. if idx >= 0 && idx < pageCount {
  573. indexs.insert(IndexSet.Element(idx))
  574. }
  575. }
  576. // self.tempPDFDocument?.removePage(at: IndexSet(integersIn: 0..<(Int(self.tempPDFDocument?.pageCount ?? 0))))
  577. _ = self.tempPDFDocument?.importPages(indexs, from: self.pdfDocument, at: 0)
  578. self.prePDFView.document = self.tempPDFDocument
  579. self.prePDFView.layoutDocumentView()
  580. self.prePDFView.goToFirstPage(nil)
  581. self.currentPageIndexTextField.stringValue = "1"
  582. self.totalPageCountLabel.stringValue = " / \(self.tempPDFDocument!.pageCount)"
  583. }
  584. @IBAction func buttonClicked_FormatSelect(_ sender: NSButton) {
  585. guard let item = self.formatSelectButton.selectedItem else { return }
  586. self.convertType = KMConvertType(rawValue: item.tag) ?? .Word
  587. updataView()
  588. }
  589. func transform(with string: String) {
  590. if string == KMLocalizedString("Create Sheet for each Table") {
  591. self.excelWorksheetOption = .forEachTable
  592. } else if string == KMLocalizedString("Create Sheet for each Page") {
  593. self.excelWorksheetOption = .forEachPage
  594. } else if string == KMLocalizedString("Create single Sheet for File") {
  595. self.excelWorksheetOption = .forTheDocument
  596. }
  597. }
  598. @IBAction func buttonClicked_excelStyle(_ sender: NSButton) {
  599. if sender.isEqual(self.onlyTextBtn) {
  600. self.tableMenu.isEnabled = false
  601. self.allContentMenu.isEnabled = false
  602. self.excelContentOption = .onlyText
  603. self.excelWorksheetOption = .forEachTable
  604. } else if (sender.isEqual(self.onlyTableBtn)) {
  605. self.tableMenu.isEnabled = true
  606. self.allContentMenu.isEnabled = false
  607. self.excelContentOption = .onlyTable
  608. transform(with: self.tableMenu.selectedItem?.title ?? "")
  609. } else if (sender.isEqual(self.allContentBtn)) {
  610. self.tableMenu.isEnabled = false
  611. self.allContentMenu.isEnabled = true
  612. self.excelContentOption = .allContent
  613. transform(with: self.allContentMenu.selectedItem?.title ?? "")
  614. }
  615. }
  616. @IBAction func buttonClicked_tableMenu(_ sender: NSButton) {
  617. transform(with: self.tableMenu.selectedItem?.title ?? "")
  618. }
  619. @IBAction func buttonClicked_allContentMenu(_ sender: NSButton) {
  620. transform(with: self.allContentMenu.selectedItem?.title ?? "")
  621. }
  622. @IBAction func buttonClicked_DpiSelect(_ sender: NSPopUpButton) {
  623. let index = sender.indexOfSelectedItem
  624. var dpi = 0
  625. if index == 0 {
  626. dpi = 50
  627. } else if index == 1 {
  628. dpi = 72
  629. } else if index == 2 {
  630. dpi = 96
  631. } else if index == 3 {
  632. dpi = 150
  633. } else if index == 4 {
  634. dpi = 300
  635. } else if index == 5 {
  636. dpi = 600
  637. }
  638. self.imageDPINumber = dpi
  639. }
  640. @IBAction func buttonClick_PreviousPage(_ sender: NSButton) {
  641. if self.prePDFView.canGoToPreviousPage() {
  642. self.prePDFView.goToPreviousPage(nil)
  643. let currentIndex = self.prePDFView.document?.index(for: self.prePDFView.currentPage()) ?? 0
  644. self.currentPageIndexTextField.stringValue = "\(currentIndex + 1)"
  645. }
  646. }
  647. @IBAction func buttonClicked_NextPage(_ sender: NSButton) {
  648. if self.prePDFView.canGoToNextPage() {
  649. self.prePDFView.goToNextPage(nil)
  650. let currentIndex = self.prePDFView.document?.index(for: self.prePDFView.currentPage())
  651. self.currentPageIndexTextField.stringValue = "\((currentIndex ?? 0) + 1)"
  652. }
  653. }
  654. @IBAction func buttonClicked_Batch(_ sender: NSButton) {
  655. if !IAPProductsManager.default().isAvailableAllFunction() {
  656. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  657. return
  658. }
  659. if self.pdfDocument?.documentURL == nil {
  660. NSSound.beep()
  661. return
  662. }
  663. if self.callBackBlock != nil {
  664. self.callBackBlock!()
  665. self.callBackBlock = nil
  666. }
  667. dismissSheet()
  668. }
  669. @IBAction func buttonClicked_Convert(_ sender: Any) {
  670. self.window?.makeFirstResponder(self.prePDFView)
  671. if (4 == pageRangeBox.indexOfSelectedItem) {
  672. if self.fileAttri_ == nil {
  673. self.fileAttri_ = KMFileAttribute()
  674. self.fileAttri_?.filePath = self.pdfDocument?.documentURL.path ?? ""
  675. }
  676. // fileAttri_.pdfDocument = self.pdfDocument
  677. self.fileAttri_?.bAllPage = false
  678. self.fileAttri_?.pagesType = .custom
  679. self.fileAttri_?.pagesString = pageRangeBox.stringValue
  680. let pages = self.fileAttri_?.fetchSelectPages() ?? []
  681. if pages.isEmpty {
  682. return
  683. }
  684. }
  685. let openPanel = NSOpenPanel()
  686. openPanel.canChooseFiles = false
  687. openPanel.canChooseDirectories = true
  688. openPanel.canCreateDirectories = true
  689. openPanel.beginSheetModal(for: self.window!) { result in
  690. if result == .OK {
  691. self.savePath = openPanel.url!.path
  692. self.beginConvert()
  693. }
  694. }
  695. }
  696. func beginConvert() {
  697. var isLimitConvert = false
  698. #if VERSION_FREE
  699. #if VERSION_DMG
  700. // 桌机版
  701. if IAPProductsManager.default().isAvailableAllFunction() {
  702. if IAPProductsManager.default().isAvailableAdvancedPDFToOffice() {
  703. isLimitConvert = false
  704. } else {
  705. if (.PNG == self.convertType ||
  706. .JPEG == self.convertType ||
  707. .JPG == self.convertType ||
  708. .HTML == self.convertType ||
  709. .Text == self.convertType ||
  710. .Word == self.convertType) {
  711. isLimitConvert = false
  712. } else {
  713. isLimitConvert = true
  714. }
  715. }
  716. } else {
  717. isLimitConvert = true
  718. }
  719. #else
  720. // 免费版
  721. if IAPProductsManager.default().isAvailableAdvancedPDFToOffice() == false {
  722. isLimitConvert = true
  723. }
  724. #endif
  725. #else
  726. // 付费版
  727. if IAPProductsManager.default().isAvailableAdvancedPDFToOffice() {
  728. isLimitConvert = false
  729. } else {
  730. if (.PNG == self.convertType ||
  731. .JPEG == self.convertType ||
  732. .JPG == self.convertType ||
  733. .HTML == self.convertType ||
  734. .Text == self.convertType ||
  735. .Word == self.convertType) {
  736. isLimitConvert = false
  737. } else {
  738. isLimitConvert = true
  739. }
  740. }
  741. #endif
  742. self.showWaitting()
  743. let pages = NSMutableArray()
  744. DispatchQueue.global(qos: .background).async { [self] in
  745. let filePath = getConvertFileSavePath()
  746. if (FileManager.default.fileExists(atPath: filePath)) {
  747. try?FileManager.default.removeItem(atPath: filePath)
  748. }
  749. if self.prePDFView.document.write(toFile: filePath) {
  750. for i in 0..<self.prePDFView.document.pageCount {
  751. pages.add(i + 1)
  752. }
  753. }
  754. DispatchQueue.main.async {
  755. if pages.count < 1 {
  756. self.hideWaitting()
  757. let alert = NSAlert()
  758. alert.alertStyle = .critical
  759. 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: ""))"
  760. alert.runModal()
  761. return
  762. }
  763. let pageCount = pages.count
  764. var selectPages = [Int]()
  765. if isLimitConvert {
  766. if pageCount >= 10 {
  767. for i in 0..<10 {
  768. selectPages.append(pages[i] as! Int)
  769. }
  770. } else {
  771. selectPages = pages as! [Int]
  772. }
  773. } else {
  774. selectPages = pages as! [Int]
  775. }
  776. var convert = KMPDFConvert()
  777. if self.convertType == .Json {
  778. convert = KMPDFConvertJson()
  779. convert.isAllInOneSheet = self.isAllInOneSheet
  780. } else if self.convertType == .AdvancedWord || self.convertType == .Word {
  781. convert = KMPDFConvertWord()
  782. let data = convert as? KMPDFConvertWord
  783. data?.layoutOptions = self.isAllInOneSheet ? .retainPageLayout : .retainFlowingText
  784. convert.isAllInOneSheet = self.isAllInOneSheet
  785. } else if self.convertType == .Excel {
  786. convert = KMPDFConvertExcel()
  787. convert.isExtractText = false
  788. convert.isExtractTable = false
  789. convert.isAllInOneSheet = self.excelWorksheetOption == .forTheDocument
  790. if self.onlyTextBtn.state == .on {
  791. convert.isExtractText = true
  792. } else if self.onlyTableBtn.state == .on {
  793. convert.isExtractTable = true
  794. convert.extractTableIndex = self.excelWorksheetOption?.rawValue ?? 0
  795. }
  796. } else if self.convertType == .PPT {
  797. convert = KMPDFConvertPPT()
  798. } else if self.convertType == .Text {
  799. convert = KMPDFConvertText()
  800. } else if self.convertType == .RTF {
  801. convert = KMPDFConvertRTF()
  802. } else if self.convertType == .HTML {
  803. convert = KMPDFConvertHTML()
  804. } else if self.convertType == .CSV {
  805. convert = KMPDFConvertCSV()
  806. convert.isExtractTable = self.extractTableButton.state == .on
  807. } else {
  808. if self.convertType == .JPEG ||
  809. self.convertType == .JPG ||
  810. self.convertType == .PNG ||
  811. self.convertType == .GIF ||
  812. self.convertType == .TIFF ||
  813. self.convertType == .TGA ||
  814. self.convertType == .BMP ||
  815. self.convertType == .JP2 {
  816. convert = KMPDFConvertImage()
  817. let data = convert as? KMPDFConvertImage
  818. if self.convertType == .JPEG {
  819. data?.imageType = .JPEG
  820. } else if self.convertType == .JPG {
  821. data?.imageType = .JPEG
  822. } else if self.convertType == .PNG {
  823. data?.imageType = .PNG
  824. }
  825. // else if self.convertType == .GIF {
  826. // } else if self.convertType == .TIFF {
  827. // } else if self.convertType == .TGA {
  828. // } else if self.convertType == .BMP {
  829. // }
  830. data?.imageDpi = self.imageDPINumber
  831. }
  832. }
  833. convert.isAllowOCR = self.ocrButton.state == .on
  834. convert.ocrLanguage = convert.isAllowOCR ? self.ocrLanguage_ : .english
  835. convert.filePath = filePath
  836. convert.pages = selectPages
  837. // convert.isAllInOneSheet = self.isAllInOneSheet
  838. if self.convertType == .Word {
  839. convert.type = 0
  840. } else {
  841. convert.type = 1
  842. }
  843. // convert.isExtractTable = self.extractTableButton.state == .on
  844. convert.outputFolderPath = self.savePath
  845. convert.outputFileName = (self.pdfDocument?.documentURL.deletingPathExtension().lastPathComponent) ?? NSLocalizedString("Untitled", comment: "")
  846. if self.convertType == .AdvancedWord {
  847. convert.convertType = .word
  848. } else if self.convertType == .JPEG ||
  849. self.convertType == .JPG ||
  850. self.convertType == .PNG ||
  851. self.convertType == .GIF ||
  852. self.convertType == .TIFF ||
  853. self.convertType == .TGA ||
  854. self.convertType == .BMP ||
  855. self.convertType == .JP2 {
  856. convert.convertType = KMPDFConvertType(rawValue: self.convertType.rawValue) ?? .word
  857. convert.options = [KMPDFConvertOptionsKeyImageDPI : self.imageDPINumber,
  858. KMPDFConvertOptionsKeyImageWithAnnotation : true] as [String : Any]
  859. } else {
  860. convert.convertType = KMPDFConvertType(rawValue: self.convertType.rawValue) ?? .word
  861. }
  862. if self.convertType == .Excel {
  863. convert.excelContentOption = self.excelContentOption
  864. convert.excelWorksheetOption = self.excelWorksheetOption
  865. }
  866. convert.password = self.lockPassword
  867. KMPDFConvertManager.defaultManager.convert(convert: convert) { [weak self] (finished, error) in
  868. self?.hideWaitting()
  869. if finished {
  870. self?.dismissSheet()
  871. if FileManager.default.fileExists(atPath: convert.outputFilePath) {
  872. let workspace = NSWorkspace.shared
  873. let url = URL(fileURLWithPath: convert.outputFilePath)
  874. workspace.activateFileViewerSelecting([url])
  875. }
  876. } else if let error = error {
  877. let err: NSError = error as NSError
  878. var erroeString = ""
  879. switch err.code {
  880. case CPDFConverterEncryptError:
  881. erroeString = NSLocalizedString("Password required or incorrect password. Please re-enter your password and try again", comment: "")
  882. break
  883. case CPDFConverterPermissionError:
  884. erroeString = NSLocalizedString("The license doesn't allow the permission", comment: "")
  885. break
  886. case CPDFConverterMallocError:
  887. erroeString = NSLocalizedString("Malloc failure", comment: "")
  888. break
  889. case CPDFConverterUnknownError:
  890. erroeString = NSLocalizedString("Unknown error in processing conversion. Please try again later", comment: "")
  891. break
  892. case CPDFConverterPDFUnknownError:
  893. erroeString = NSLocalizedString("Unknown error in processing PDF. Please try again later", comment: "")
  894. break
  895. case CPDFConverterPDFFileError:
  896. erroeString = NSLocalizedString("File not found or could not be opened. Check if your file exists or choose another file to convert", comment: "")
  897. break
  898. case CPDFConverterPDFFormatError:
  899. erroeString = NSLocalizedString("File not in PDF format or corruptead. Change a PDF file and try again", comment: "")
  900. break
  901. case CPDFConverterPDFSecurityError:
  902. erroeString = NSLocalizedString("Unsupported security scheme", comment: "")
  903. break
  904. case CPDFConverterPDFPageError:
  905. erroeString = NSLocalizedString("Page not found or content error", comment: "")
  906. break
  907. default:
  908. erroeString = NSLocalizedString("Table not found", comment: "")
  909. break
  910. }
  911. let alert = NSAlert()
  912. alert.alertStyle = .critical
  913. alert.messageText = NSLocalizedString("Conversion Failed", comment: "")
  914. alert.informativeText = erroeString
  915. alert.addButton(withTitle: NSLocalizedString("OK", comment: ""))
  916. if #available(OSX 10.14, *) {
  917. alert.beginSheetModal(for: self?.window! ?? NSWindow.currentWindow(), completionHandler: nil)
  918. } else {
  919. alert.runModal()
  920. }
  921. }
  922. }
  923. }
  924. }
  925. }
  926. func getConvertFileSavePath() -> String {
  927. var path = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.applicationSupportDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).last
  928. path?.append("/")
  929. path?.append(Bundle.main.bundleIdentifier!)
  930. if (FileManager.default.fileExists(atPath: path!) == false) {
  931. try?FileManager.default.createDirectory(atPath: path!, withIntermediateDirectories: false)
  932. }
  933. path?.append("/")
  934. path?.append("convert.pdf")
  935. return path!
  936. }
  937. @IBAction func buttonClicked_MoreConvert(_ sender: NSButton) {
  938. if sender == self.moreButton {
  939. FMTrackEventManager.defaultManager.trackEvent(event: "PUW", withProperties: ["PUW_Btn": "Btn_PUW_Converter_Premium_UnlimitedConvertw"])
  940. } else if sender == self.upgradeButton {
  941. FMTrackEventManager.defaultManager.trackEvent(event: "PUW", withProperties: ["PUW_Btn": "Btn_PUW_Converter_Premium_Upgrade"])
  942. }
  943. #if VERSION_DMG
  944. if IAPProductsManager.default().isAvailableAllFunction() && !IAPProductsManager.default().isAvailableAdvancedPDFToOffice() {
  945. let limitWC = KMPurchaseLimitWindowController.currentLimitWC()
  946. limitWC.continueBlock = { windowController in
  947. }
  948. limitWC.window?.center()
  949. limitWC.showWindow(nil)
  950. } else {
  951. let winC = KMPurchaseCompareWindowController.sharedInstance()
  952. if convertType == .Word || convertType == .AdvancedWord {
  953. winC?.kEventName = "Reading_PDFtoWord_BuyNow"
  954. } else if convertType == .Excel {
  955. winC?.kEventName = "Reading_PDFtoExcel_BuyNow"
  956. } else if convertType == .PPT {
  957. winC?.kEventName = "Reading_PDFtoPPT_BuyNow"
  958. } else if convertType == .RTF {
  959. winC?.kEventName = "Reading_PDFtoRTF_BuyNow"
  960. } else if convertType == .CSV {
  961. winC?.kEventName = "Reading_PDFtoCSV_BuyNow"
  962. } else if convertType == .Text {
  963. winC?.kEventName = "Reading_PDFtoText_BuyNow"
  964. }
  965. if convertType == .JPEG || convertType == .JPG || convertType == .PNG || convertType == .GIF || convertType == .TIFF || convertType == .TGA || convertType == .BMP || convertType == .JP2 {
  966. winC?.kEventName = "Reading_PDFtoImage_BuyNow"
  967. }
  968. // else if convertType == . {
  969. // winC?.kEventName = "Reading_PDFtoExcel_BuyNow"
  970. // }
  971. winC?.showWindow(nil)
  972. }
  973. #else
  974. if IAPProductsManager.default().isAvailableAllFunction() {
  975. var vc: KMToolCompareWindowController? = nil
  976. if convertType == .Word || convertType == .AdvancedWord {
  977. // vc = KMToolCompareWindowController(toolType: .Convert, selectNum: 1)
  978. vc = KMToolCompareWindowController.toolCompare(toolType: .Convert, selectNum: 1)
  979. } else if convertType == .Excel {
  980. // vc = KMToolCompareWindowController(toolType: .Convert, selectNum: 2)
  981. vc = KMToolCompareWindowController.toolCompare(toolType: .Convert, selectNum: 2)
  982. } else if convertType == .PPT {
  983. // vc = KMToolCompareWindowController(toolType: .Convert, selectNum: 3)
  984. vc = KMToolCompareWindowController.toolCompare(toolType: .Convert, selectNum: 3)
  985. } else if convertType.rawValue < 15 && convertType.rawValue > 7 {
  986. // vc = KMToolCompareWindowController(toolType: .Convert, selectNum: 4)
  987. vc = KMToolCompareWindowController.toolCompare(toolType: .Convert, selectNum: 4)
  988. } else {
  989. // vc = KMToolCompareWindowController(toolType: .Convert, selectNum: 0)
  990. vc = KMToolCompareWindowController.toolCompare(toolType: .Convert, selectNum: 0)
  991. }
  992. vc?.showWindow(nil)
  993. } else {
  994. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  995. }
  996. #endif
  997. self.buttonClicked_Cancel(self.cancelButton)
  998. }
  999. @IBAction func buttonItemClick_SepSingle(_ sender: Any) {
  1000. if .on == self.singleButton.state {
  1001. self.isAllInOneSheet = true
  1002. } else {
  1003. self.isAllInOneSheet = false
  1004. }
  1005. }
  1006. func controlTextDidEndEditing(_ obj: Notification) {
  1007. let object = obj.object
  1008. if (object as AnyObject).isEqual(self.currentPageIndexTextField) == true {
  1009. let num: Int = Int(self.currentPageIndexTextField.stringValue) ?? 1
  1010. let targetPage = self.prePDFView.document.page(at: UInt(num - 1))
  1011. self.prePDFView.go(to: targetPage)
  1012. } else if (object as AnyObject).isEqual(self.pageRangeBox) == true {
  1013. // guard self.handInputButton.state == .on else { return }
  1014. let idx = self.pageRangeBox.indexOfSelectedItem
  1015. if idx >= 0 && idx <= 3 { // 0 1 2 3
  1016. return
  1017. } else {
  1018. // if self.pageRangeBox.indexOfSelectedItem != 4 { // 页面范围切换中
  1019. }
  1020. if self.fileAttri_ == nil {
  1021. self.fileAttri_ = KMFileAttribute()
  1022. self.fileAttri_?.filePath = self.pdfDocument?.documentURL.path ?? ""
  1023. }
  1024. // fileAttribute.pdfDocument = self.pdfDocument
  1025. self.fileAttri_?.bAllPage = false
  1026. self.fileAttri_?.pagesType = .custom
  1027. self.fileAttri_?.pagesString = self.pageRangeBox.stringValue
  1028. let pages = self.fileAttri_?.fetchSelectPages() ?? []
  1029. if pages.count > 0 {
  1030. let pagesArray = NSMutableArray()
  1031. for pageNum in pages {
  1032. let tpage = self.pdfDocument?.page(at: UInt(pageNum - 1))
  1033. pagesArray.add(tpage as Any)
  1034. }
  1035. self.produceNewPDF(with: pagesArray as! [CPDFPage])
  1036. } else {
  1037. self.showCriticalAlert(nil)
  1038. }
  1039. }
  1040. }
  1041. func controlTextDidChange(_ obj: Notification) {
  1042. if let textField = obj.object as? NSComboBox {
  1043. if textField.isEqual(pageRangeBox) {
  1044. if let stringValue = self.currentPageIndexTextField.formatter?.string(for: NSNumber(value: Float(self.currentPageIndexTextField.stringValue) ?? 0)) {
  1045. if let integerValue = Int(stringValue) {
  1046. var string = stringValue
  1047. if integerValue > self.prePDFView.document.pageCount {
  1048. string = "1-\(self.prePDFView.document.pageCount)"
  1049. } else if integerValue <= 0 {
  1050. string = "1"
  1051. }
  1052. self.currentPageIndexTextField.stringValue = string
  1053. }
  1054. }
  1055. }
  1056. }
  1057. }
  1058. @IBAction func comboxClicked_PageRange(_ sender: NSComboBox) {
  1059. if (0 == pageRangeBox.indexOfSelectedItem ||
  1060. 1 == pageRangeBox.indexOfSelectedItem ||
  1061. 2 == pageRangeBox.indexOfSelectedItem ||
  1062. 3 == pageRangeBox.indexOfSelectedItem) {
  1063. self.window?.makeFirstResponder(self)
  1064. pageRangeBox.isEditable = false
  1065. pageRangeBox.delegate = nil
  1066. } else {
  1067. pageRangeBox.stringValue = pageRangeBox.stringValue
  1068. pageRangeBox.isEditable = true
  1069. pageRangeBox.delegate = self
  1070. self.window?.makeFirstResponder(pageRangeBox)
  1071. }
  1072. self.lockPassword = ""
  1073. let pagesArray = NSMutableArray()
  1074. for i in 0..<(self.pdfDocument?.pageCount ?? 0) {
  1075. let copyPage = self.pdfDocument?.page(at: i)
  1076. pagesArray.add(copyPage!)
  1077. }
  1078. if (2 == pageRangeBox.indexOfSelectedItem) {
  1079. pagesArray.subArray(type: .Odd)
  1080. produceNewPDF(with: pagesArray as! [CPDFPage])
  1081. } else if (3 == pageRangeBox.indexOfSelectedItem) {
  1082. pagesArray.subArray(type: .Even)
  1083. produceNewPDF(with: pagesArray as! [CPDFPage])
  1084. } else if (1 == pageRangeBox.indexOfSelectedItem) {
  1085. pagesArray.removeAllObjects()
  1086. let page = self.prePDFView.currentPage()
  1087. if (page != nil) {
  1088. pagesArray.add(page as Any)
  1089. }
  1090. produceNewPDF(with: pagesArray as! [CPDFPage])
  1091. } else if 0 == pageRangeBox.indexOfSelectedItem {
  1092. produceNewPDF(with: pagesArray as! [CPDFPage])
  1093. }
  1094. }
  1095. @IBAction func comboxClicked_OcrLanguage(_ sender: AnyObject?) {
  1096. switch (ocrLanguageBox.indexOfSelectedItem) {
  1097. case 0: //chinese
  1098. self.ocrLanguage_ = .chinese
  1099. break
  1100. case 1: //chinese zht
  1101. self.ocrLanguage_ = .chineseTraditional
  1102. break
  1103. case 2: //English
  1104. self.ocrLanguage_ = .english
  1105. break
  1106. case 3:
  1107. //Japanese
  1108. self.ocrLanguage_ = .japanese
  1109. break
  1110. case 4:
  1111. //Kroean
  1112. self.ocrLanguage_ = .korean
  1113. break
  1114. case 5:
  1115. //Serbian
  1116. self.ocrLanguage_ = .serbian
  1117. break
  1118. case 6:
  1119. //Occitan
  1120. self.ocrLanguage_ = .occitan
  1121. break
  1122. case 7:
  1123. //Danish
  1124. self.ocrLanguage_ = .danish
  1125. break
  1126. case 8:
  1127. //German
  1128. self.ocrLanguage_ = .german
  1129. break
  1130. case 9:
  1131. //French
  1132. self.ocrLanguage_ = .french
  1133. break
  1134. case 10:
  1135. //Italian
  1136. self.ocrLanguage_ = .italian
  1137. break
  1138. case 11:
  1139. //Spanish
  1140. self.ocrLanguage_ = .spanish
  1141. break
  1142. case 12:
  1143. //Portuguese
  1144. self.ocrLanguage_ = .portuguese
  1145. break
  1146. case 13:
  1147. //Maori
  1148. self.ocrLanguage_ = .maori
  1149. break
  1150. case 14:
  1151. //Malay
  1152. self.ocrLanguage_ = .malay
  1153. break
  1154. case 15:
  1155. //Malay
  1156. self.ocrLanguage_ = .maltese
  1157. break
  1158. case 16:
  1159. //Dutch
  1160. self.ocrLanguage_ = .dutch
  1161. break
  1162. case 17:
  1163. //Norwegian
  1164. self.ocrLanguage_ = .norwegian
  1165. break
  1166. case 18:
  1167. //Polish
  1168. self.ocrLanguage_ = .polish
  1169. break
  1170. case 19:
  1171. //Romanian
  1172. self.ocrLanguage_ = .romanian
  1173. break
  1174. case 20:
  1175. //Slovak
  1176. self.ocrLanguage_ = .slovak
  1177. break
  1178. case 21:
  1179. //Slovenian
  1180. self.ocrLanguage_ = .slovenian
  1181. break
  1182. case 22:
  1183. //Albanian
  1184. self.ocrLanguage_ = .albanian
  1185. break
  1186. case 23:
  1187. //Swedish
  1188. self.ocrLanguage_ = .swedish
  1189. break
  1190. case 24:
  1191. //Swahili
  1192. self.ocrLanguage_ = .swahili
  1193. break
  1194. case 25:
  1195. //Tagalog
  1196. self.ocrLanguage_ = .tagalog
  1197. break
  1198. case 26:
  1199. //Turish
  1200. self.ocrLanguage_ = .turish
  1201. break
  1202. case 27:
  1203. //Uzbek
  1204. self.ocrLanguage_ = .uzbek
  1205. break
  1206. case 28:
  1207. //Vietnamese
  1208. self.ocrLanguage_ = .vietnamese
  1209. break
  1210. case 29:
  1211. //Afrikaans
  1212. self.ocrLanguage_ = .afrikaans
  1213. break
  1214. case 30:
  1215. //Azerbaijani
  1216. self.ocrLanguage_ = .azerbaijani
  1217. break
  1218. case 31:
  1219. //Bosnian
  1220. self.ocrLanguage_ = .bosnian
  1221. break
  1222. case 32:
  1223. //Czech
  1224. self.ocrLanguage_ = .czech
  1225. break
  1226. case 33: //Welsh
  1227. self.ocrLanguage_ = .welsh
  1228. break
  1229. case 34: //Estonian
  1230. self.ocrLanguage_ = .estonian
  1231. break
  1232. case 35: //Irish
  1233. self.ocrLanguage_ = .irish
  1234. break
  1235. case 36: //Croatian
  1236. self.ocrLanguage_ = .croatian
  1237. break
  1238. case 37: //Hungarian
  1239. self.ocrLanguage_ = .hungarian
  1240. break
  1241. case 38: //Indonesian
  1242. self.ocrLanguage_ = .indonesian
  1243. break
  1244. case 39: //Icelandic
  1245. self.ocrLanguage_ = .icelandic
  1246. break
  1247. case 40: //Kurdish
  1248. self.ocrLanguage_ = .kurdish
  1249. break
  1250. case 41: //Lithuanian
  1251. self.ocrLanguage_ = .lithuanian
  1252. break
  1253. case 42: //Latvian
  1254. self.ocrLanguage_ = .latvian
  1255. break
  1256. case 43: //Marathi
  1257. self.ocrLanguage_ = .marathi
  1258. break
  1259. case 44: //Nepali
  1260. self.ocrLanguage_ = .nepali
  1261. break
  1262. case 45: //Latvia
  1263. self.ocrLanguage_ = .latvian
  1264. break
  1265. case 46: //Bihari
  1266. self.ocrLanguage_ = .bihari
  1267. break
  1268. case 47: //Maithili
  1269. self.ocrLanguage_ = .maithili
  1270. break
  1271. case 48: //Angika
  1272. self.ocrLanguage_ = .angika
  1273. break
  1274. case 49: //Bhojpuri
  1275. self.ocrLanguage_ = .bhojpuri
  1276. break
  1277. case 50: //Magahi
  1278. self.ocrLanguage_ = .magahi
  1279. break
  1280. case 51: //Nagpur
  1281. self.ocrLanguage_ = .nagpur
  1282. break
  1283. case 52: //Newari
  1284. self.ocrLanguage_ = .newari
  1285. break
  1286. case 53: //GoanKonkani
  1287. self.ocrLanguage_ = .goanKonkani
  1288. break
  1289. case 54: //SaudiArabia
  1290. self.ocrLanguage_ = .saudiArabia
  1291. break
  1292. default:
  1293. self.ocrLanguage_ = .english
  1294. break
  1295. }
  1296. }
  1297. @IBAction func comboxClicked_SupoortOCR(_ sender: AnyObject?) {
  1298. if(ocrButton.state == .on) {
  1299. ocrLabel.textColor = KMAppearance.titleColor()
  1300. ocrLanguageBox.isEnabled = true
  1301. } else {
  1302. ocrLabel.textColor = KMAppearance.Layout.h2Color()
  1303. ocrLanguageBox.isEnabled = false
  1304. }
  1305. }
  1306. }
  1307. @objc enum KMSubArrayType: Int {
  1308. case Odd = 0
  1309. case Even
  1310. }
  1311. extension NSMutableArray{
  1312. func subArray(type: KMSubArrayType) {
  1313. if self.count == 0 { return }
  1314. if type.rawValue > 1 || type.rawValue < 0 { return }
  1315. let newArray = NSMutableArray()
  1316. for i in 0..<self.count {
  1317. if i % 2 == type.rawValue {
  1318. newArray.add(self[i])
  1319. }
  1320. }
  1321. self.removeAllObjects()
  1322. self.addObjects(from: newArray as! [Any])
  1323. }
  1324. }