KMTools.swift 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616
  1. //
  2. // KMTools.swift
  3. // PDF Master
  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: - 获取 App 版本号
  85. @objc class func getAppVersion() -> String {
  86. let infoDictionary = Bundle.main.infoDictionary
  87. if (infoDictionary == nil) {
  88. return "1.0.0"
  89. }
  90. var version = infoDictionary!["CFBundleShortVersionString"]
  91. if (version != nil && (version is String) && (version as! String).isEmpty == false) {
  92. return version as! String
  93. }
  94. version = infoDictionary!["CFBundleVersion"]
  95. if (version != nil && (version is String) && (version as! String).isEmpty == false) {
  96. return version as! String
  97. }
  98. return "1.0.0"
  99. }
  100. class func getSystemVersion() -> (Int, Int, Int) {
  101. let versionInfo = ProcessInfo.processInfo.operatingSystemVersion
  102. return (versionInfo.majorVersion, versionInfo.minorVersion, versionInfo.patchVersion)
  103. }
  104. @objc class func isDefaultPDFReader() -> Bool {
  105. let app = LSCopyDefaultRoleHandlerForContentType("pdf" as CFString, LSRolesMask.all)?.takeUnretainedValue()
  106. if (app == nil) {
  107. return false
  108. }
  109. return (app! as String) == Bundle.main.bundleIdentifier!
  110. }
  111. @objc class func setDefaultPDFReader(_ isOrNo: Bool) -> Bool {
  112. var bid = "com.apple.Preview"
  113. if (isOrNo) {
  114. bid = Bundle.main.bundleIdentifier!
  115. }
  116. let status: OSStatus = LSSetDefaultRoleHandlerForContentType(KMTools.UTIforFileExtension("pdf") as CFString, LSRolesMask.all, bid as CFString)
  117. if (status == 0) {
  118. return true
  119. }
  120. return false
  121. }
  122. @objc class func UTIforFileExtension(_ exn: String) -> String {
  123. return (UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, exn as CFString, nil)?.takeUnretainedValue())! as String
  124. }
  125. // MARK: - 是否全屏
  126. @objc class func isFullScreen(_ window: NSWindow) -> Bool {
  127. return window.styleMask.contains(.fullScreen)
  128. }
  129. // MARK: - 文件类型
  130. static let imageExtensions = ["jpg","cur","bmp","jpeg","gif","png","tiff","tif",/*@"pic",*/"ico","icns","tga","psd","eps","hdr","jp2","jpc","pict","sgi","heic"]
  131. static let pdfExtensions = ["pdf"]
  132. static let officeExtensions = ["doc", "docx", "xls", "xlsx", "ppt", "pptx"]
  133. @objc class func isImageType(_ exn: String) -> Bool {
  134. return KMTools.imageExtensions.contains(exn.lowercased())
  135. }
  136. @objc class func isPDFType(_ exn: String) -> Bool {
  137. return KMTools.pdfExtensions.contains(exn.lowercased())
  138. }
  139. @objc class func isOfficeType(_ exn: String) -> Bool {
  140. return KMTools.officeExtensions.contains(exn.lowercased())
  141. }
  142. @objc class func getUniqueFilePath(filePath: String) -> String {
  143. var isDirectory: ObjCBool = false
  144. var uniqueFilePath = filePath
  145. let fileManager = FileManager.default
  146. fileManager.fileExists(atPath: uniqueFilePath, isDirectory: &isDirectory)
  147. var i = 0
  148. if (isDirectory.boolValue) {
  149. while fileManager.fileExists(atPath: uniqueFilePath) {
  150. i += 1
  151. uniqueFilePath = "\(filePath)(\(i))"
  152. }
  153. } else {
  154. let fileURL = URL(fileURLWithPath: filePath)
  155. let path = fileURL.deletingPathExtension().path
  156. while fileManager.fileExists(atPath: uniqueFilePath) {
  157. i += 1
  158. uniqueFilePath = "\(path)(\(i).\(fileURL.pathExtension)"
  159. }
  160. }
  161. return uniqueFilePath
  162. }
  163. @objc class func getTempFloderPath() -> String? {
  164. return NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.applicationSupportDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).last?.stringByAppendingPathComponent(Bundle.main.bundleIdentifier!).stringByAppendingPathComponent("KMTemp")
  165. }
  166. // MARK: - Document isDocumentEdited
  167. @objc class func setDocumentEditedState(window: NSWindow) {
  168. guard let _document = NSDocumentController.shared.document(for: window) else {
  169. return
  170. }
  171. self.setDocumentEditedState(document: _document)
  172. }
  173. @objc class func setDocumentEditedState(url: URL) {
  174. guard let _document = NSDocumentController.shared.document(for: url) else {
  175. return
  176. }
  177. self.setDocumentEditedState(document: _document)
  178. }
  179. @objc class func setDocumentEditedState(document: NSDocument) {
  180. km_synchronized(document) {
  181. document.updateChangeCount(.changeDone)
  182. }
  183. }
  184. @objc class func clearDocumentEditedState(window: NSWindow) {
  185. guard let _document = NSDocumentController.shared.document(for: window) else {
  186. return
  187. }
  188. self.clearDocumentEditedState(document: _document)
  189. }
  190. @objc class func clearDocumentEditedState(url: URL) {
  191. guard let _document = NSDocumentController.shared.document(for: url) else {
  192. return
  193. }
  194. self.clearDocumentEditedState(document: _document)
  195. }
  196. @objc class func clearDocumentEditedState(document: NSDocument) {
  197. km_synchronized(document) {
  198. document.updateChangeCount(.changeCleared)
  199. }
  200. }
  201. }
  202. // MARK: - PDFMaster
  203. let kKMPurchaseProductURLString = "https://www.pdfreaderpro.com/store"
  204. extension KMTools {
  205. // 打开 [快速教学]
  206. @objc class func openQuickStartStudy() {
  207. // MARK: -
  208. // MARK: 内嵌文档需要替换
  209. var fileName = "PDF Master User Guide"
  210. let fileType = "pdf"
  211. let path = Bundle.main.path(forResource: fileName, ofType: fileType)
  212. if (path == nil || FileManager.default.fileExists(atPath: path!) == false) {
  213. KMTools.openURL(url: URL(string: "https://www.pdfreaderpro.com/help"))
  214. return
  215. }
  216. let version = KMTools.getAppVersion()
  217. fileName.append(" v\(version).\(fileType)")
  218. let folderPath = NSSearchPathForDirectoriesInDomains(.applicationSupportDirectory, .userDomainMask, true).last?.appending("/\(Bundle.main.bundleIdentifier!)")
  219. if (FileManager.default.fileExists(atPath: folderPath!) == false) {
  220. try?FileManager.default.createDirectory(atPath: folderPath!, withIntermediateDirectories: false)
  221. }
  222. let toPath = "\(folderPath!)/\(fileName)"
  223. if (FileManager.default.fileExists(atPath: toPath)) {
  224. try?FileManager.default.removeItem(atPath: toPath)
  225. }
  226. try?FileManager.default.copyItem(atPath: path!, toPath: toPath)
  227. if !toPath.isPDFValid() {
  228. let alert = NSAlert()
  229. alert.alertStyle = .critical
  230. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  231. alert.runModal()
  232. return
  233. }
  234. NSDocumentController.shared.openDocument(withContentsOf: URL(fileURLWithPath: toPath), display: true) { document, result, error in
  235. if (error != nil) {
  236. NSApp.presentError(error!)
  237. }
  238. }
  239. }
  240. // 打开 [FAQ] 网站
  241. @objc class func openFAQWebsite() {
  242. // KMTools.openURL(URL(string: "")!)
  243. }
  244. // 打开 [更多产品] 网站
  245. @objc class func openMoreProductWebsite() {
  246. KMTools.openURL(url: URL(string: "https://www.pdfreaderpro.com/product?utm_source=MacApp&utm_campaign=ProductLink&utm_medium=PdfProduct"))
  247. }
  248. // 打开 [免费 PDF 模板] 网站
  249. @objc class func openFreePDFTemplatesWebsite() {
  250. KMTools.openURL(url: URL(string: "https://www.pdfreaderpro.com/templates?utm_source=MacApp&utm_campaign=TemplatesLink&utm_medium=PdfTemplates"))
  251. }
  252. // 打开 [ComPDFKit 授权] 网站
  253. @objc class func openComPDFKitPowerWebsite() {
  254. KMTools.openURL(url: URL(string: "https://www.compdf.com/?utm_source=macapp&utm_medium=pdfmac&utm_campaign=compdfkit-promp"))
  255. }
  256. // 打开 [官网 下载页] 网站
  257. // 测试环境 http://test-pdf-pro.kdan.cn:3021/pdf-master-mac-download
  258. @objc class func openDownloadDMGWebsite() {
  259. KMTools.openURL(urlString: "https://www.pdfreaderpro.com/pdf-master-mac-download")
  260. }
  261. @objc class func openPurchaseProductWebsite() {
  262. KMTools.openURL(urlString: kKMPurchaseProductURLString)
  263. }
  264. // 意见反馈
  265. @objc class func feekback() {
  266. let (major, minor, bugFix) = KMTools.getSystemVersion()
  267. let versionInfoString = "\(KMTools.getRawSystemInfo()) - \(major).\(minor).\(bugFix)"
  268. let appVersion = KMTools.getAppVersion()
  269. let appName = KMTools.getAppName()
  270. let subjects = "\(appName) - \(appVersion);\(NSLocalizedString("Propose a New Feature", comment: ""));\(versionInfoString)"
  271. // MARK: -
  272. // MARK TODO: 邮箱域名需要替换
  273. let email = "support@pdfreaderpro.com"
  274. // MARK: -
  275. // MARK TODO: 邮箱域名需要替换
  276. KMMailHelper.newEmail(withContacts: email, andSubjects: subjects)
  277. }
  278. @objc class func getRawSystemInfo() -> String {
  279. let info = GBDeviceInfo.deviceInfo().rawSystemInfoString
  280. if (info == nil) {
  281. return ""
  282. }
  283. return info!
  284. }
  285. @objc class func getAppName() -> String {
  286. let appTarget = KMTools_OC.getAppTarget()
  287. if (appTarget == .free) {
  288. return "PDF Master"
  289. } else if (appTarget == .pro) {
  290. return "PDF Master Pro"
  291. } else if (appTarget == .DMG) {
  292. // return "PDF Master DMG"
  293. return "PDF Master"
  294. }
  295. return "PDF Master"
  296. }
  297. @objc class func pageRangeTypeString(pageRange: KMPageRange) -> String {
  298. switch pageRange {
  299. case .all:
  300. return NSLocalizedString("All Pages", comment: "")
  301. case .current:
  302. return NSLocalizedString("Current Page", comment: "")
  303. case .odd:
  304. return NSLocalizedString("Odd Pages", comment: "")
  305. case .even:
  306. return NSLocalizedString("Even Pages", comment: "")
  307. case .custom:
  308. return NSLocalizedString("Customize", comment: "")
  309. case .horizontal:
  310. return NSLocalizedString("Horizontal Pages", comment: "")
  311. case .vertical:
  312. return NSLocalizedString("Vertical Pages", comment: "")
  313. }
  314. }
  315. @objc class func pageRangePlaceholderString() -> String {
  316. return NSLocalizedString("e.g. 1,3-5,10", comment: "")
  317. }
  318. @objc class func saveWatermarkDocumentToTemp(document: CPDFDocument, secureOptions: [CPDFDocumentWriteOption : Any]? = nil, removePWD: Bool = false) -> URL? {
  319. // 将文档存入临时目录
  320. if let data = self.getTempFloderPath(), !FileManager.default.fileExists(atPath: data) {
  321. try?FileManager.default.createDirectory(atPath: data, withIntermediateDirectories: false)
  322. }
  323. guard let filePath = self.getTempFloderPath()?.stringByAppendingPathComponent("temp_saveDocumentFor_temp.pdf") else {
  324. return nil
  325. }
  326. // 清除临时数据
  327. if (FileManager.default.fileExists(atPath: filePath)) {
  328. try?FileManager.default.removeItem(atPath: filePath)
  329. }
  330. return self.saveWatermarkDocument(document: document, to: URL(fileURLWithPath: filePath), secureOptions: secureOptions, removePWD: removePWD)
  331. }
  332. @objc class func saveWatermarkDocument(document: CPDFDocument, to url: URL, secureOptions: [CPDFDocumentWriteOption : Any]? = nil, removePWD: Bool = false) -> URL? {
  333. guard let _document = self._saveDocumentForWatermark(document: document) else {
  334. return nil
  335. }
  336. // 保存文档
  337. if let data = secureOptions, !data.isEmpty {
  338. _document.write(to: url, withOptions: data)
  339. } else if (removePWD) {
  340. _document.writeDecrypt(to: url)
  341. } else {
  342. _document.write(to: url)
  343. }
  344. // 清除临时数据
  345. if let _fileUrl = _document.documentURL, FileManager.default.fileExists(atPath: _fileUrl.path) {
  346. try?FileManager.default.removeItem(atPath: _fileUrl.path)
  347. }
  348. return url
  349. }
  350. @objc class func saveWatermarkDocumentForCompress(document: CPDFDocument, to url: URL, imageQuality: Int) -> URL? {
  351. guard let _document = self._saveDocumentForWatermark(document: document) else {
  352. return nil
  353. }
  354. // _document.write(to: _document.documentURL)
  355. // 保存文档
  356. let result = _document.writeOptimize(to: url, withOptions: [.imageQualityOption : imageQuality])
  357. // 清除临时数据
  358. if let _fileUrl = _document.documentURL, FileManager.default.fileExists(atPath: _fileUrl.path) {
  359. try?FileManager.default.removeItem(atPath: _fileUrl.path)
  360. }
  361. if (result) {
  362. return url
  363. }
  364. return nil
  365. }
  366. @objc class func saveWatermarkDocumentForFlatten(document: CPDFDocument, to url: URL) -> URL? {
  367. guard let _document = self._saveDocumentForWatermark(document: document) else {
  368. return nil
  369. }
  370. // 保存文档
  371. let result = _document.writeFlatten(to: url)
  372. // 清除临时数据
  373. if let _fileUrl = _document.documentURL, FileManager.default.fileExists(atPath: _fileUrl.path) {
  374. try?FileManager.default.removeItem(atPath: _fileUrl.path)
  375. }
  376. if (result) {
  377. return url
  378. }
  379. return nil
  380. }
  381. @objc class func saveDocumentToTemp(document: CPDFDocument, fileID: String, needUnlock: Bool = true) -> URL? {
  382. // 将文档存入临时目录
  383. if let data = self.getTempFloderPath(), !FileManager.default.fileExists(atPath: data) {
  384. try?FileManager.default.createDirectory(atPath: data, withIntermediateDirectories: false)
  385. }
  386. guard let filePath = self.getTempFloderPath()?.stringByAppendingPathComponent("temp_saveDocumentFor\(fileID).pdf") else {
  387. return nil
  388. }
  389. // 清除临时数据
  390. if (FileManager.default.fileExists(atPath: filePath)) {
  391. try?FileManager.default.removeItem(atPath: filePath)
  392. }
  393. document.write(toFile: filePath)
  394. if (!FileManager.default.fileExists(atPath: filePath)) {
  395. return nil
  396. }
  397. guard let _document = CPDFDocument(url: URL(fileURLWithPath: filePath)) else {
  398. return nil
  399. }
  400. if (!needUnlock) {
  401. return _document.documentURL
  402. }
  403. // 如果加锁,则去解锁
  404. if let pwd = document.password, !pwd.isEmpty, _document.isLocked {
  405. _document.unlock(withPassword: document.password)
  406. }
  407. if (_document.isLocked) {
  408. return nil
  409. }
  410. return _document.documentURL
  411. }
  412. @objc class func trackEvent(type: KMSubscribeWaterMarkType) -> Void {
  413. if (type == .stamp) {
  414. KMAnalytics.trackEvent(eventName: "PDFMaster_Subscribe_Stamp", parameters: nil, appTarget: .all)
  415. } else if (type == .link) {
  416. KMAnalytics.trackEvent(eventName: "PDFMaster_Subscribe_Link", parameters: nil, appTarget: .all)
  417. } else if (type == .sign) {
  418. KMAnalytics.trackEvent(eventName: "PDFMaster_Subscribe_Sign", parameters: nil, appTarget: .all)
  419. } else if (type == .editText) {
  420. KMAnalytics.trackEvent(eventName: "PDFMaster_Subscribe_EditText", parameters: nil, appTarget: .all)
  421. } else if (type == .editImage) {
  422. KMAnalytics.trackEvent(eventName: "PDFMaster_Subscribe_EditImage", parameters: nil, appTarget: .all)
  423. } else if (type == .insert) {
  424. KMAnalytics.trackEvent(eventName: "PDFMaster_Subscribe_Insert", parameters: nil, appTarget: .all)
  425. } else if (type == .extract) {
  426. KMAnalytics.trackEvent(eventName: "PDFMaster_Subscribe_Extract", parameters: nil, appTarget: .all)
  427. } else if (type == .replace) {
  428. KMAnalytics.trackEvent(eventName: "PDFMaster_Subscribe_Replace", parameters: nil, appTarget: .all)
  429. } else if (type == .split) {
  430. KMAnalytics.trackEvent(eventName: "PDFMaster_Subscribe_Split", parameters: nil, appTarget: .all)
  431. } else if (type == .delete) {
  432. KMAnalytics.trackEvent(eventName: "PDFMaster_Subscribe_Delete", parameters: nil, appTarget: .all)
  433. } else if (type == .rotate) {
  434. KMAnalytics.trackEvent(eventName: "PDFMaster_Subscribe_Rotate", parameters: nil, appTarget: .all)
  435. } else if (type == .copy) {
  436. KMAnalytics.trackEvent(eventName: "PDFMaster_Subscribe_Copy", parameters: nil, appTarget: .all)
  437. } else if (type == .toWord) {
  438. KMAnalytics.trackEvent(eventName: "PDFMaster_Subscribe_ToWord", parameters: nil, appTarget: .all)
  439. } else if (type == .toExcel) {
  440. KMAnalytics.trackEvent(eventName: "PDFMaster_Subscribe_ToExcel", parameters: nil, appTarget: .all)
  441. } else if (type == .toPPT) {
  442. KMAnalytics.trackEvent(eventName: "PDFMaster_Subscribe_ToPPT", parameters: nil, appTarget: .all)
  443. } else if (type == .toRTF) {
  444. KMAnalytics.trackEvent(eventName: "PDFMaster_Subscribe_ToRTF", parameters: nil, appTarget: .all)
  445. } else if (type == .toCSV) {
  446. KMAnalytics.trackEvent(eventName: "PDFMaster_Subscribe_ToCSV", parameters: nil, appTarget: .all)
  447. } else if (type == .toHTML) {
  448. KMAnalytics.trackEvent(eventName: "PDFMaster_Subscribe_ToHTML", parameters: nil, appTarget: .all)
  449. } else if (type == .toText) {
  450. KMAnalytics.trackEvent(eventName: "PDFMaster_Subscribe_ToText", parameters: nil, appTarget: .all)
  451. } else if (type == .toImage) {
  452. KMAnalytics.trackEvent(eventName: "PDFMaster_Subscribe_ToImage", parameters: nil, appTarget: .all)
  453. } else if (type == .compress) {
  454. KMAnalytics.trackEvent(eventName: "PDFMaster_Subscribe_Compress", parameters: nil, appTarget: .all)
  455. } else if (type == .merge) {
  456. KMAnalytics.trackEvent(eventName: "PDFMaster_Subscribe_Merge", parameters: nil, appTarget: .all)
  457. } else if (type == .setPassword) {
  458. KMAnalytics.trackEvent(eventName: "PDFMaster_Subscribe_SetPassword", parameters: nil, appTarget: .all)
  459. } else if (type == .removePassword) {
  460. KMAnalytics.trackEvent(eventName: "PDFMaster_Subscribe_RemovePassword", parameters: nil, appTarget: .all)
  461. } else if (type == .crop) {
  462. KMAnalytics.trackEvent(eventName: "PDFMaster_Subscribe_Crop", parameters: nil, appTarget: .all)
  463. } else if (type == .aiTranslate) {
  464. KMAnalytics.trackEvent(eventName: "PDFMaster_Subscribe_AITranslate", parameters: nil, appTarget: .all)
  465. } else if (type == .aiRewrite) {
  466. KMAnalytics.trackEvent(eventName: "PDFMaster_Subscribe_AIRewrite", parameters: nil, appTarget: .all)
  467. } else if (type == .aiCorrect) {
  468. KMAnalytics.trackEvent(eventName: "PDFMaster_Subscribe_AICorrect", parameters: nil, appTarget: .all)
  469. }
  470. }
  471. // MARK: - Private Methods
  472. @objc fileprivate class func _documentAddWatermark(document: CPDFDocument) -> CPDFDocument? {
  473. // 添加水印
  474. let watermark = CPDFWatermark(document: document, type: .image)
  475. watermark?.image = NSImage(named: "KMImageNameWatermark")
  476. watermark?.horizontalPosition = .left
  477. watermark?.verticalPosition = .top
  478. watermark?.scale = 0.5
  479. document.addWatermark(watermark)
  480. // 添加 link注释
  481. var watermarkAnnoBounds = NSMakeRect(0, 0, 120, 32)
  482. for i in 0 ..< document.pageCount {
  483. guard let page = document.page(at: i) else {
  484. continue
  485. }
  486. // 水印注释 frame
  487. watermarkAnnoBounds.origin.y = page.bounds.size.height-watermarkAnnoBounds.size.height
  488. // 找到需要删除的水印注释(之前添加)
  489. var flagAnnos: [CPDFAnnotation] = []
  490. for anno in page.annotations {
  491. if let anno_link = anno as? CPDFLinkAnnotation, anno_link.url() == kKMPurchaseProductURLString, anno_link.bounds.equalTo(watermarkAnnoBounds) {
  492. flagAnnos.append(anno_link)
  493. }
  494. }
  495. // 删除之前的水印注释
  496. for anno in flagAnnos {
  497. page.removeAnnotation(anno)
  498. }
  499. // 新增新的水印注释
  500. let anno = CPDFLinkAnnotation(document: document)
  501. anno?.bounds = watermarkAnnoBounds
  502. anno?.setURL(kKMPurchaseProductURLString)
  503. page.addAnnotation(anno)
  504. }
  505. return document
  506. }
  507. @objc fileprivate class func _saveDocumentForWatermark(document: CPDFDocument) -> CPDFDocument? {
  508. // 将文档存入临时目录
  509. guard let _fileUrl = self.saveDocumentToTemp(document: document, fileID: "Watermark") else {
  510. return nil
  511. }
  512. guard let _document = CPDFDocument(url: _fileUrl) else {
  513. return nil
  514. }
  515. // 如果加锁,则去解锁
  516. if let pwd = document.password, !pwd.isEmpty, _document.isLocked {
  517. _document.unlock(withPassword: pwd)
  518. }
  519. // 添加水印
  520. return self._documentAddWatermark(document: _document)
  521. }
  522. }