KMConvertWindowController.swift 64 KB

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