KMTools.swift 32 KB

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