KMTools.swift 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819
  1. //
  2. // KMTools.swift
  3. // PDF Reader Pro
  4. //
  5. // Created by tangchao on 2023/3/7.
  6. //
  7. import Cocoa
  8. @objc class KMTools: NSObject {
  9. // MARK: - 获取已打开的文件
  10. @objc class func getOpenDocumentURLs() -> [URL] {
  11. var files:[URL] = []
  12. for window in NSApp.windows {
  13. if ((window.windowController is KMBrowserWindowController) == false) {
  14. continue
  15. }
  16. let controller: KMBrowserWindowController = window.windowController as! KMBrowserWindowController
  17. let model = controller.browser?.tabStripModel
  18. guard let count = model?.count() else {
  19. continue
  20. }
  21. if (count <= 0) {
  22. continue
  23. }
  24. for i in 0 ..< count {
  25. let document = model?.tabContents(at: Int32(i))
  26. if (document?.fileURL == nil) {
  27. continue
  28. }
  29. if (document?.isHome == nil || document!.isHome) {
  30. continue
  31. }
  32. files.append((document?.fileURL)!)
  33. }
  34. }
  35. return files
  36. }
  37. // MARK: - 无法区分 [权限+开启] [开启] 这两种情况 请不要使用
  38. private class func isDocumentHasPermissionsPassword(_ url: URL) -> Bool {
  39. let document = PDFDocument(url: url)
  40. if (document == nil) {
  41. return false
  42. }
  43. if (document?.permissionsStatus == .user) {
  44. return true
  45. }
  46. // document?.permissionsStatus == .none
  47. if (document!.isLocked == false) { // 没有加锁
  48. return false
  49. }
  50. // 已加锁 [权限+开启] [开启]
  51. if (KMTools.hasPermissionsLimit(document!)) { // 有权限限制
  52. return true
  53. }
  54. return false
  55. }
  56. // MARK: - 暂时只处理了复制和打印两项(后续项目需求有新增时,可以再此方法里扩展)
  57. @objc class func hasPermissionsLimit(_ document: PDFDocument) -> Bool {
  58. if (document.allowsCopying == false) {
  59. return true
  60. }
  61. if (document.allowsPrinting == false) {
  62. return true
  63. }
  64. return false
  65. }
  66. // MARK: - 打开网页
  67. @objc class func openURL(url: URL?) {
  68. guard let _url = url else {
  69. KMPrint("url invalid.")
  70. return
  71. }
  72. NSWorkspace.shared.open(_url)
  73. }
  74. @objc class func openURL(urlString: String?) {
  75. guard let _urlString = urlString else {
  76. KMPrint("url invalid.")
  77. return
  78. }
  79. KMTools.openURL(url: URL(string: _urlString))
  80. }
  81. // MARK: - 查看文件
  82. @objc class func viewFile(at filepath: String) {
  83. let ws = NSWorkspace.shared
  84. let url = URL(fileURLWithPath: filepath)
  85. ws.activateFileViewerSelecting([url])
  86. }
  87. // MARK: - 获取 App 版本号
  88. @objc class func getAppVersion() -> String {
  89. let infoDictionary = Bundle.main.infoDictionary
  90. if (infoDictionary == nil) {
  91. return "1.0.0"
  92. }
  93. var version = infoDictionary!["CFBundleShortVersionString"]
  94. if (version != nil && (version is String) && (version as! String).isEmpty == false) {
  95. return version as! String
  96. }
  97. version = infoDictionary!["CFBundleVersion"]
  98. if (version != nil && (version is String) && (version as! String).isEmpty == false) {
  99. return version as! String
  100. }
  101. return "1.0.0"
  102. }
  103. class func getSystemVersion() -> (Int, Int, Int) {
  104. let versionInfo = ProcessInfo.processInfo.operatingSystemVersion
  105. return (versionInfo.majorVersion, versionInfo.minorVersion, versionInfo.patchVersion)
  106. }
  107. @objc class func isDefaultPDFReader() -> Bool {
  108. let app = LSCopyDefaultRoleHandlerForContentType("pdf" as CFString, LSRolesMask.all)?.takeUnretainedValue()
  109. if (app == nil) {
  110. return false
  111. }
  112. return (app! as String) == Bundle.main.bundleIdentifier!
  113. }
  114. @objc class func setDefaultPDFReader(_ isOrNo: Bool) -> Bool {
  115. var bid = "com.apple.Preview"
  116. if (isOrNo) {
  117. bid = Bundle.main.bundleIdentifier!
  118. }
  119. let status: OSStatus = LSSetDefaultRoleHandlerForContentType(KMTools.UTIforFileExtension("pdf") as CFString, LSRolesMask.all, bid as CFString)
  120. if (status == 0) {
  121. return true
  122. }
  123. return false
  124. }
  125. @objc class func UTIforFileExtension(_ exn: String) -> String {
  126. return (UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, exn as CFString, nil)?.takeUnretainedValue())! as String
  127. }
  128. // MARK: - 是否全屏
  129. @objc class func isFullScreen(_ window: NSWindow) -> Bool {
  130. return window.styleMask.contains(.fullScreen)
  131. }
  132. // MARK: - 文件类型
  133. static let imageExtensions = ["jpg","cur","bmp","jpeg","gif","png","tiff","tif",/*@"pic",*/"ico","icns","tga","psd","eps","hdr","jp2","jpc","pict","sgi","heic"]
  134. static let pdfExtensions = ["pdf"]
  135. static let officeExtensions = ["doc", "docx", "xls", "xlsx", "ppt", "pptx"]
  136. @objc class func isImageType(_ exn: String) -> Bool {
  137. return KMTools.imageExtensions.contains(exn.lowercased())
  138. }
  139. @objc class func isPDFType(_ exn: String) -> Bool {
  140. return KMTools.pdfExtensions.contains(exn.lowercased())
  141. }
  142. @objc class func isOfficeType(_ exn: String) -> Bool {
  143. return KMTools.officeExtensions.contains(exn.lowercased())
  144. }
  145. @objc class func getUniqueFilePath(filePath: String) -> String {
  146. var isDirectory: ObjCBool = false
  147. var uniqueFilePath = filePath
  148. let fileManager = FileManager.default
  149. fileManager.fileExists(atPath: uniqueFilePath, isDirectory: &isDirectory)
  150. var i = 0
  151. if (isDirectory.boolValue) {
  152. while fileManager.fileExists(atPath: uniqueFilePath) {
  153. i += 1
  154. uniqueFilePath = "\(filePath)(\(i))"
  155. }
  156. } else {
  157. let fileURL = URL(fileURLWithPath: filePath)
  158. let path = fileURL.deletingPathExtension().path
  159. while fileManager.fileExists(atPath: uniqueFilePath) {
  160. i += 1
  161. uniqueFilePath = "\(path)(\(i)).\(fileURL.pathExtension)"
  162. }
  163. }
  164. return uniqueFilePath
  165. }
  166. @objc class func getTempFloderPath() -> String? {
  167. return self.getTempRootPath()?.stringByAppendingPathComponent("KMTemp")
  168. }
  169. @objc class func getTempRootPath() -> String? {
  170. return NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.applicationSupportDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).last?.stringByAppendingPathComponent(Bundle.main.bundleIdentifier!)
  171. }
  172. // MARK: - Document isDocumentEdited
  173. @objc class func setDocumentEditedState(window: NSWindow) {
  174. guard let _document = NSDocumentController.shared.document(for: window) else {
  175. return
  176. }
  177. self.setDocumentEditedState(document: _document)
  178. }
  179. @objc class func setDocumentEditedState(url: URL) {
  180. guard let _document = NSDocumentController.shared.document(for: url) else {
  181. return
  182. }
  183. self.setDocumentEditedState(document: _document)
  184. }
  185. @objc class func setDocumentEditedState(document: NSDocument) {
  186. km_synchronized(document) {
  187. document.updateChangeCount(.changeDone)
  188. }
  189. }
  190. @objc class func clearDocumentEditedState(window: NSWindow) {
  191. guard let _document = NSDocumentController.shared.document(for: window) else {
  192. return
  193. }
  194. self.clearDocumentEditedState(document: _document)
  195. }
  196. @objc class func clearDocumentEditedState(url: URL) {
  197. guard let _document = NSDocumentController.shared.document(for: url) else {
  198. return
  199. }
  200. self.clearDocumentEditedState(document: _document)
  201. }
  202. @objc class func clearDocumentEditedState(document: NSDocument) {
  203. km_synchronized(document) {
  204. document.updateChangeCount(.changeCleared)
  205. }
  206. }
  207. // MARK: - 解析 [1-3,5-7]
  208. @objc class func parseIndexSet(indexSet: IndexSet) -> String {
  209. return self.parseIndexs(indexs: indexSet.sorted())
  210. }
  211. @objc class func parseIndexs(indexs: [Int]) -> String {
  212. if (indexs.isEmpty) {
  213. return ""
  214. }
  215. if (indexs.count == 1) {
  216. return "\(indexs.first!+1)"
  217. }
  218. var sortArray: [Int] = []
  219. for i in indexs {
  220. sortArray.append(i)
  221. }
  222. /// 排序 (升序)
  223. sortArray.sort(){$0 < $1}
  224. var a: Int = 0
  225. var b: Int = 0
  226. var result: String?
  227. for i in sortArray {
  228. if (result == nil) {
  229. a = i
  230. b = i
  231. result = ""
  232. continue
  233. }
  234. if (i == b+1) {
  235. b = i
  236. if (i == sortArray.last) {
  237. result?.append(String(format: "%d-%d", a+1,b+1))
  238. }
  239. } else {
  240. if (a == b) {
  241. result?.append(String(format: "%d,", a+1))
  242. } else {
  243. result?.append(String(format: "%d-%d,", a+1,b+1))
  244. }
  245. a = i
  246. b = i
  247. if (i == sortArray.last) {
  248. result?.append(String(format: "%d", a+1))
  249. }
  250. }
  251. }
  252. return result ?? ""
  253. }
  254. }
  255. // MARK: - PDFReaderPro
  256. let KMNCompanyWebsite = NSLocalizedString("https://www.pdfreaderpro.com", comment: "")
  257. let APPMain_Link = NSLocalizedString("https://www.pdfreaderpro.com/mac", comment: "")
  258. //跳转Store界面
  259. let Store_Link = NSLocalizedString("https://www.pdfreaderpro.com/store", comment: "")
  260. //PDF to office pack
  261. let PDFToOfficePacket_Link = NSLocalizedString("https://www.pdfreaderpro.com/store/upgrade?utm_source=appdmg&utm_medium=toptbr&utm_campaign=pdftooffice", comment: "")
  262. //跨平台
  263. let CrossPlatform_Link = NSLocalizedString("https://www.pdfreaderpro.com/store/pdf-pro-permanent-cross-platform-package?utm_source=appdmg&utm_medium=toptbr&utm_campaign=crossplatform", comment: "")
  264. //AI包
  265. let AIProduct_Link = NSLocalizedString("https://www.pdfreaderpro.com/store/aitools?utm_source=appdmg&utm_medium=allapp&utm_campaign=aitool", comment: "")
  266. //教育折扣
  267. let Store_Edu_Link = NSLocalizedString("https://www.pdfreaderpro.com/store?mode=edu&utm_source=appdmg&utm_medium=toptbr&utm_campaign=edu", comment: "")
  268. let APP_Privacy_Policy_URL = NSLocalizedString("https://www.pdfreaderpro.com/privacy-policy", comment: "")
  269. let APP_Terms_Of_Service_URL = NSLocalizedString("https://www.pdfreaderpro.com/terms_of_service", comment: "")
  270. // MARK: - 快速工具
  271. extension KMTools {
  272. // 打开 [快速教学]
  273. @objc class func openQuickStartStudy() {
  274. var fileName = NSLocalizedString("Quick Start Guide.pdf", comment: "")
  275. let fileType = "pdf"
  276. let path = Bundle.main.path(forResource: fileName, ofType: "")
  277. if (path == nil || FileManager.default.fileExists(atPath: path!) == false) {
  278. KMTools.openURL(url: URL(string: "https://www.pdfreaderpro.com/help"))
  279. return
  280. }
  281. let version = KMTools.getAppVersion()
  282. fileName.append(" v\(version).\(fileType)")
  283. let folderPath = NSSearchPathForDirectoriesInDomains(.applicationSupportDirectory, .userDomainMask, true).last?.appending("/\(Bundle.main.bundleIdentifier!)")
  284. if (FileManager.default.fileExists(atPath: folderPath!) == false) {
  285. try?FileManager.default.createDirectory(atPath: folderPath!, withIntermediateDirectories: false)
  286. }
  287. let toPath = "\(folderPath!)/\(fileName)"
  288. if (FileManager.default.fileExists(atPath: toPath)) {
  289. try?FileManager.default.removeItem(atPath: toPath)
  290. }
  291. try?FileManager.default.copyItem(atPath: path!, toPath: toPath)
  292. NSDocumentController.shared.km_safe_openDocument(withContentsOf: URL(fileURLWithPath: toPath), display: true) { _, _, _ in
  293. }
  294. }
  295. // 打开 [FAQ] 网站
  296. @objc class func openFAQWebsite() {
  297. var tStrUrl: String?
  298. #if VERSION_FREE
  299. #if VERSION_DMG
  300. tStrUrl = "https://www.pdfreaderpro.com/help?utm_source=MacAppDmg&utm_campaign=HelpLink&utm_medium=PdfHelp"
  301. #else
  302. tStrUrl = "https://www.pdfreaderpro.com/help?utm_source=MacAppLite&utm_campaign=HelpLink&utm_medium=PdfHelp"
  303. #endif
  304. #else
  305. tStrUrl = "https://www.pdfreaderpro.com/help?utm_source=MacApp&utm_campaign=HelpLink&utm_medium=PdfHelp"
  306. #endif
  307. KMTools.openURL(urlString: tStrUrl)
  308. }
  309. // 打开 [更多产品] 网站
  310. @objc class func openMoreProductWebsite() {
  311. var tStrUrl: String?
  312. if KMKdanRemoteConfig.remoteConfig.showHelp_More_RecommendLink() {
  313. #if VERSION_FREE
  314. tStrUrl = "https://www.pdfreaderpro.com/product?utm_source=MacAppLite&utm_campaign=ProductLink&utm_medium=PdfProduct"
  315. #else
  316. tStrUrl = "https://www.pdfreaderpro.com/product?utm_source=MacApp&utm_campaign=ProductLink&utm_medium=PdfProduct"
  317. #endif
  318. } else {
  319. tStrUrl = "https://apps.apple.com/developer/pdf-technologies-inc/id1263126485"
  320. }
  321. #if VERSION_DMG
  322. tStrUrl = "https://www.pdfreaderpro.com/product?utm_source=MacAppDmg&utm_campaign=ProductLink&utm_medium=PdfProduct"
  323. #endif
  324. KMTools.openURL(urlString: tStrUrl)
  325. }
  326. // 打开 [免费 PDF 模板] 网站
  327. @objc class func openFreePDFTemplatesWebsite() {
  328. var tStrUrl: String?
  329. #if VERSION_FREE
  330. #if VERSION_DMG
  331. tStrUrl = "https://www.pdfreaderpro.com/templates?utm_source=MacAppDmg&utm_campaign=TemplatesLink&utm_medium=PdfTemplates"
  332. #else
  333. tStrUrl = "https://www.pdfreaderpro.com/templates?utm_source=MacAppLite&utm_campaign=TemplatesLink&utm_medium=PdfTemplates"
  334. #endif
  335. #else
  336. tStrUrl = "https://www.pdfreaderpro.com/templates?utm_source=MacApp&utm_campaign=TemplatesLink&utm_medium=PdfTemplates"
  337. #endif
  338. KMTools.openURL(urlString: tStrUrl)
  339. }
  340. // 打开 [ComPDFKit 授权] 网站
  341. @objc class func openComPDFKitPowerWebsite() {
  342. KMTools.openURL(url: URL(string: "https://www.compdf.com?utm_source=macapp&utm_medium=pdfmac&utm_campaign=compdfkit-promp"))
  343. }
  344. // 打开 [官网 下载页] 网站
  345. // 测试环境 http://test-pdf-pro.kdan.cn:3021/pdf-master-mac-download
  346. @objc class func openDownloadDMGWebsite() {
  347. KMTools.openURL(urlString: "https://www.pdfreaderpro.com/pdf-master-mac-download")
  348. }
  349. @objc class func openPurchaseProductWebsite() {
  350. KMTools.openURL(urlString: Store_Link)
  351. }
  352. @objc class func openVPPWebSite() {
  353. var tStrHttpUrl = "https://www.pdfreaderpro.com/vpp-purchase-program"
  354. #if VERSION_DMG
  355. tStrHttpUrl = KMNCompanyWebsite + "/vpp-purchase-program?utm_source=pdfdmg&utm_campaign=menubar_vpp"
  356. #else
  357. tStrHttpUrl = KMNCompanyWebsite + "/vpp-purchase-program?utm_source=pdfmacstore&utm_campaign=menubar_vpp"
  358. #endif
  359. KMTools.openURL(urlString: tStrHttpUrl)
  360. }
  361. @objc class func openEducateWebSite() {
  362. let tStrHttpUrl = KMLocalizedString("https://www.pdfreaderpro.com/store?mode=edu#utm_source=mac_app&utm_medium=pdf_pro_dmg&utm_content=menu_bar_click")
  363. KMTools.openURL(urlString: tStrHttpUrl)
  364. }
  365. @objc class func openPrivacyPolicyWebSite() {
  366. KMTools.openURL(urlString: APP_Privacy_Policy_URL)
  367. }
  368. @objc class func openTermOfServiceWebSite() {
  369. KMTools.openURL(urlString: APP_Terms_Of_Service_URL)
  370. }
  371. }
  372. extension KMTools {
  373. // 意见反馈
  374. @objc class func feekback() {
  375. let (major, minor, bugFix) = KMTools.getSystemVersion()
  376. let versionInfoString = "\(KMTools.getRawSystemInfo()) - \(major).\(minor).\(bugFix)"
  377. let appVersion = KMTools.getAppVersion()
  378. let appName = KMTools.getAppNameForSupportEmail()
  379. let subjects = "\(appName) - \(appVersion);\(NSLocalizedString("Feedback", comment: ""));\(versionInfoString)"
  380. let email = "support@pdfreaderpro.com"
  381. KMMailHelper.newEmail(withContacts: email, andSubjects: subjects)
  382. }
  383. //
  384. @objc class func reportBug() {
  385. let (major, minor, bugFix) = KMTools.getSystemVersion()
  386. let versionInfoString = "\(KMTools.getRawSystemInfo()) - \(major).\(minor).\(bugFix)"
  387. let appVersion = KMTools.getAppVersion()
  388. let appName = KMTools.getAppNameForSupportEmail()
  389. let subjects = "\(appName) - \(appVersion);\(NSLocalizedString("Report a Bug", comment: ""));\(versionInfoString)"
  390. let email = "support@pdfreaderpro.com"
  391. KMMailHelper.newEmail(withContacts: email, andSubjects: subjects)
  392. }
  393. //
  394. @objc class func proposeNewFeature() {
  395. let (major, minor, bugFix) = KMTools.getSystemVersion()
  396. let versionInfoString = "\(KMTools.getRawSystemInfo()) - \(major).\(minor).\(bugFix)"
  397. let appVersion = KMTools.getAppVersion()
  398. let appName = KMTools.getAppNameForSupportEmail()
  399. let subjects = "\(appName) - \(appVersion);\(NSLocalizedString("Propose a New Feature", comment: ""));\(versionInfoString)"
  400. let email = "support@pdfreaderpro.com"
  401. KMMailHelper.newEmail(withContacts: email, andSubjects: subjects)
  402. }
  403. @objc class func reportGeneralQuestions() {
  404. let (major, minor, bugFix) = KMTools.getSystemVersion()
  405. let versionInfoString = "\(KMTools.getRawSystemInfo()) - \(major).\(minor).\(bugFix)"
  406. let appVersion = KMTools.getAppVersion()
  407. let appName = KMTools.getAppNameForSupportEmail()
  408. let subjects = "\(appName) - \(appVersion);\(NSLocalizedString("General Questions", comment: ""));\(versionInfoString)"
  409. let email = "support@pdfreaderpro.com"
  410. KMMailHelper.newEmail(withContacts: email, andSubjects: subjects)
  411. }
  412. @objc class func rateUs() {
  413. #if VERSION_FREE
  414. iRate.sharedInstance().appStoreID = 919472673
  415. #else
  416. iRate.sharedInstance().appStoreID = 825459243
  417. #endif
  418. if UserDefaults.standard.bool(forKey: "kUserHaveClickRateUsKey") == false {
  419. UserDefaults.standard.set(true, forKey: "kUserHaveClickRateUsKey")
  420. UserDefaults.standard.synchronize()
  421. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "kUserHaveClickRateUsNotification"), object: self)
  422. }
  423. iRate.sharedInstance().openRatingsPageInAppStore()
  424. }
  425. }
  426. extension KMTools {
  427. @objc class func getAppNameForSupportEmail() -> String {
  428. var tAppName = "PDF Reader Pro"
  429. #if VERSION_FREE
  430. #if VERSION_DMG
  431. #if VERSION_BETA
  432. tAppName = "PDF Reader Pro Beta"
  433. #endif
  434. // 桌机版
  435. if let tManager = VerificationManager.default() {
  436. let status = tManager.status
  437. if status == ActivityStatusTrial {
  438. tAppName = "\(tAppName) Trial"
  439. } else if status == ActivityStatusVerification {
  440. tAppName = "\(tAppName) Verification"
  441. } else if status == ActivityStatusTrialExpire {
  442. tAppName = "\(tAppName) TrialExpire"
  443. } else if status == ActivityStatusVerifExpire {
  444. tAppName = "\(tAppName) VerifExpire"
  445. }
  446. }
  447. #else
  448. // AppStore 免费版本
  449. tAppName = "PDF Reader Pro Lite"
  450. #endif
  451. #else
  452. // AppStore 付费版
  453. tAppName = "PDF Reader Pro Edition"
  454. #endif
  455. return tAppName
  456. }
  457. @objc class func getRawSystemInfo() -> String {
  458. let info = GBDeviceInfo.deviceInfo().rawSystemInfoString
  459. if (info == nil) {
  460. return ""
  461. }
  462. return info!
  463. }
  464. @objc class func getAppName() -> String {
  465. return "PDF Reader Pro"
  466. }
  467. @objc class func pageRangeTypeString(pageRange: KMPageRange) -> String {
  468. switch pageRange {
  469. case .all:
  470. return NSLocalizedString("All Pages", comment: "")
  471. case .current:
  472. return NSLocalizedString("Current Page", comment: "")
  473. case .odd:
  474. return NSLocalizedString("Odd Pages", comment: "")
  475. case .even:
  476. return NSLocalizedString("Even Pages", comment: "")
  477. case .custom:
  478. return NSLocalizedString("Customize", comment: "")
  479. case .horizontal:
  480. return NSLocalizedString("Horizontal Pages", comment: "")
  481. case .vertical:
  482. return NSLocalizedString("Vertical Pages", comment: "")
  483. }
  484. }
  485. @objc class func pageRangePlaceholderString() -> String {
  486. return NSLocalizedString("e.g. 1,3-5,10", comment: "")
  487. }
  488. @objc class func saveWatermarkDocumentToTemp(document: CPDFDocument, secureOptions: [CPDFDocumentWriteOption : Any]? = nil, removePWD: Bool = false) -> URL? {
  489. // 将文档存入临时目录
  490. if let data = self.getTempFloderPath(), !FileManager.default.fileExists(atPath: data) {
  491. try?FileManager.default.createDirectory(atPath: data, withIntermediateDirectories: false)
  492. }
  493. guard let filePath = self.getTempFloderPath()?.stringByAppendingPathComponent("temp_saveDocumentFor_temp.pdf") else {
  494. return nil
  495. }
  496. // 清除临时数据
  497. if (FileManager.default.fileExists(atPath: filePath)) {
  498. try?FileManager.default.removeItem(atPath: filePath)
  499. }
  500. return self.saveWatermarkDocument(document: document, to: URL(fileURLWithPath: filePath), secureOptions: secureOptions, removePWD: removePWD)
  501. }
  502. @objc class func saveWatermarkDocument(document: CPDFDocument, to url: URL, secureOptions: [CPDFDocumentWriteOption : Any]? = nil, documentAttribute: [CPDFDocumentAttribute : Any]? = nil, removePWD: Bool = false) -> URL? {
  503. guard let _document = self._saveDocumentForWatermark(document: document) else {
  504. return nil
  505. }
  506. // 保存文档
  507. if let data = secureOptions, !data.isEmpty {
  508. _document.setDocumentAttributes(documentAttribute)
  509. _document.write(to: url, withOptions: data)
  510. } else if (removePWD) {
  511. _document.writeDecrypt(to: url)
  512. } else {
  513. _document.write(to: url)
  514. }
  515. // 清除临时数据
  516. if let _fileUrl = _document.documentURL, FileManager.default.fileExists(atPath: _fileUrl.path) {
  517. try?FileManager.default.removeItem(atPath: _fileUrl.path)
  518. }
  519. return url
  520. }
  521. @objc class func saveWatermarkDocumentForCompress(document: CPDFDocument, to url: URL, imageQuality: Int) -> URL? {
  522. guard let _document = self._saveDocumentForWatermark(document: document) else {
  523. return nil
  524. }
  525. // _document.write(to: _document.documentURL)
  526. // 保存文档
  527. let result = _document.writeOptimize(to: url, withOptions: [.imageQualityOption : imageQuality])
  528. // 清除临时数据
  529. if let _fileUrl = _document.documentURL, FileManager.default.fileExists(atPath: _fileUrl.path) {
  530. try?FileManager.default.removeItem(atPath: _fileUrl.path)
  531. }
  532. if (result) {
  533. return url
  534. }
  535. return nil
  536. }
  537. @objc class func saveWatermarkDocumentForFlatten(document: CPDFDocument, to url: URL) -> URL? {
  538. guard let _document = self._saveDocumentForWatermark(document: document) else {
  539. return nil
  540. }
  541. // 保存文档
  542. let result = _document.writeFlatten(to: url)
  543. // 清除临时数据
  544. if let _fileUrl = _document.documentURL, FileManager.default.fileExists(atPath: _fileUrl.path) {
  545. try?FileManager.default.removeItem(atPath: _fileUrl.path)
  546. }
  547. if (result) {
  548. return url
  549. }
  550. return nil
  551. }
  552. @objc class func saveDocumentToTemp(document: CPDFDocument, fileID: String, needUnlock: Bool = true) -> URL? {
  553. // 将文档存入临时目录
  554. if let data = self.getTempFloderPath(), !FileManager.default.fileExists(atPath: data) {
  555. if let rootPath = self.getTempRootPath(), !FileManager.default.fileExists(atPath: rootPath) {
  556. try?FileManager.default.createDirectory(atPath: rootPath, withIntermediateDirectories: false)
  557. }
  558. try?FileManager.default.createDirectory(atPath: data, withIntermediateDirectories: false)
  559. }
  560. guard let filePath = self.getTempFloderPath()?.stringByAppendingPathComponent("temp_saveDocumentFor\(fileID).pdf") else {
  561. return nil
  562. }
  563. // 清除临时数据
  564. if (FileManager.default.fileExists(atPath: filePath)) {
  565. try?FileManager.default.removeItem(atPath: filePath)
  566. }
  567. document.write(toFile: filePath)
  568. if (!FileManager.default.fileExists(atPath: filePath)) {
  569. return nil
  570. }
  571. guard let _document = CPDFDocument(url: URL(fileURLWithPath: filePath)) else {
  572. return nil
  573. }
  574. if (!needUnlock) {
  575. return _document.documentURL
  576. }
  577. // 如果加锁,则去解锁
  578. if let pwd = document.password, !pwd.isEmpty, _document.isLocked {
  579. _document.unlock(withPassword: document.password)
  580. }
  581. if (_document.isLocked) {
  582. return nil
  583. }
  584. return _document.documentURL
  585. }
  586. @objc class func trackEvent(type: KMSubscribeWaterMarkType) -> Void {
  587. }
  588. private static var dateFormatter_: DateFormatter?
  589. @objc class func timeString(timeDate date: Date) -> String {
  590. if dateFormatter_ == nil {
  591. dateFormatter_ = DateFormatter()
  592. }
  593. let calendar = Calendar.current
  594. let nowCmps = calendar.dateComponents([.day, .month, .year], from: Date())
  595. let currentCmps = calendar.dateComponents([.day, .month, .year], from: date)
  596. if (currentCmps.year == nowCmps.year) {
  597. if (currentCmps.month == nowCmps.month && currentCmps.day == nowCmps.day) {
  598. dateFormatter_?.dateFormat = "HH:mm"
  599. } else {
  600. dateFormatter_?.dateFormat = "MM-dd, HH:mm"
  601. }
  602. } else {
  603. dateFormatter_?.dateFormat = "yyyy-MM-dd, HH:mm"
  604. }
  605. return dateFormatter_?.string(from: date) ?? ""
  606. }
  607. @objc class func timeString(timeDate date: Date, formatString: String) -> String {
  608. if dateFormatter_ == nil {
  609. dateFormatter_ = DateFormatter()
  610. }
  611. let calendar = Calendar.current
  612. let nowCmps = calendar.dateComponents([.day, .month, .year], from: Date())
  613. let currentCmps = calendar.dateComponents([.day, .month, .year], from: date)
  614. dateFormatter_?.dateFormat = formatString
  615. return dateFormatter_?.string(from: date) ?? ""
  616. }
  617. @objc class func isFileGreaterThan10MB(atPath filePath: String) -> Bool {
  618. let fileManager = FileManager.default
  619. do {
  620. let fileAttributes = try fileManager.attributesOfItem(atPath: filePath)
  621. if let fileSize = fileAttributes[.size] as? UInt64 {
  622. let megabyteSize = fileSize / (1024 * 1024)
  623. return megabyteSize >= 10
  624. }
  625. } catch {
  626. KMPrint("Error: \(error)")
  627. }
  628. return false
  629. }
  630. // MARK: - Private Methods
  631. @objc fileprivate class func _documentAddWatermark(document: CPDFDocument) -> CPDFDocument? {
  632. // 添加水印
  633. let watermark = CPDFWatermark(document: document, type: .image)
  634. watermark?.image = NSImage(named: "KMImageNameWatermark")
  635. watermark?.horizontalPosition = .left
  636. watermark?.verticalPosition = .top
  637. watermark?.scale = 0.5
  638. document.addWatermark(watermark)
  639. // 添加 link注释
  640. var watermarkAnnoBounds = NSMakeRect(0, 0, 120, 32)
  641. for i in 0 ..< document.pageCount {
  642. guard let page = document.page(at: i) else {
  643. continue
  644. }
  645. // 水印注释 frame
  646. watermarkAnnoBounds.origin.y = page.bounds.size.height-watermarkAnnoBounds.size.height
  647. // 找到需要删除的水印注释(之前添加)
  648. var flagAnnos: [CPDFAnnotation] = []
  649. for anno in page.annotations {
  650. if let anno_link = anno as? CPDFLinkAnnotation, anno_link.url() == Store_Link, anno_link.bounds.equalTo(watermarkAnnoBounds) {
  651. flagAnnos.append(anno_link)
  652. }
  653. }
  654. // 删除之前的水印注释
  655. for anno in flagAnnos {
  656. page.removeAnnotation(anno)
  657. }
  658. // 新增新的水印注释
  659. let anno = CPDFLinkAnnotation(document: document)
  660. anno?.bounds = watermarkAnnoBounds
  661. anno?.setURL(Store_Link)
  662. page.addAnnotation(anno)
  663. }
  664. return document
  665. }
  666. @objc fileprivate class func _saveDocumentForWatermark(document: CPDFDocument) -> CPDFDocument? {
  667. // 将文档存入临时目录
  668. guard let _fileUrl = self.saveDocumentToTemp(document: document, fileID: "Watermark") else {
  669. return nil
  670. }
  671. guard let _document = CPDFDocument(url: _fileUrl) else {
  672. return nil
  673. }
  674. // 如果加锁,则去解锁
  675. if let pwd = document.password, !pwd.isEmpty, _document.isLocked {
  676. _document.unlock(withPassword: pwd)
  677. }
  678. // 添加水印
  679. return self._documentAddWatermark(document: _document)
  680. }
  681. }