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: - 查看文件
  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. }
  211. // MARK: - PDFMaster
  212. let kKMPurchaseProductURLString = "https://www.pdfreaderpro.com/store"
  213. extension KMTools {
  214. // 打开 [快速教学]
  215. @objc class func openQuickStartStudy() {
  216. // MARK: -
  217. // MARK: 内嵌文档需要替换
  218. var fileName = "PDF Master User Guide"
  219. let fileType = "pdf"
  220. let path = Bundle.main.path(forResource: fileName, ofType: fileType)
  221. if (path == nil || FileManager.default.fileExists(atPath: path!) == false) {
  222. KMTools.openURL(url: URL(string: "https://www.pdfreaderpro.com/help"))
  223. return
  224. }
  225. let version = KMTools.getAppVersion()
  226. fileName.append(" v\(version).\(fileType)")
  227. let folderPath = NSSearchPathForDirectoriesInDomains(.applicationSupportDirectory, .userDomainMask, true).last?.appending("/\(Bundle.main.bundleIdentifier!)")
  228. if (FileManager.default.fileExists(atPath: folderPath!) == false) {
  229. try?FileManager.default.createDirectory(atPath: folderPath!, withIntermediateDirectories: false)
  230. }
  231. let toPath = "\(folderPath!)/\(fileName)"
  232. if (FileManager.default.fileExists(atPath: toPath)) {
  233. try?FileManager.default.removeItem(atPath: toPath)
  234. }
  235. try?FileManager.default.copyItem(atPath: path!, toPath: toPath)
  236. NSDocumentController.shared.km_safe_openDocument(withContentsOf: URL(fileURLWithPath: toPath), display: true) { _, _, _ in
  237. }
  238. }
  239. // 打开 [FAQ] 网站
  240. @objc class func openFAQWebsite() {
  241. // KMTools.openURL(URL(string: "")!)
  242. }
  243. // 打开 [更多产品] 网站
  244. @objc class func openMoreProductWebsite() {
  245. KMTools.openURL(url: URL(string: "https://www.pdfreaderpro.com/product?utm_source=MacApp&utm_campaign=ProductLink&utm_medium=PdfProduct"))
  246. }
  247. // 打开 [免费 PDF 模板] 网站
  248. @objc class func openFreePDFTemplatesWebsite() {
  249. KMTools.openURL(url: URL(string: "https://www.pdfreaderpro.com/templates?utm_source=MacApp&utm_campaign=TemplatesLink&utm_medium=PdfTemplates"))
  250. }
  251. // 打开 [ComPDFKit 授权] 网站
  252. @objc class func openComPDFKitPowerWebsite() {
  253. KMTools.openURL(url: URL(string: "https://www.compdf.com/?utm_source=macapp&utm_medium=pdfmac&utm_campaign=compdfkit-promp"))
  254. }
  255. // 打开 [官网 下载页] 网站
  256. // 测试环境 http://test-pdf-pro.kdan.cn:3021/pdf-master-mac-download
  257. @objc class func openDownloadDMGWebsite() {
  258. KMTools.openURL(urlString: "https://www.pdfreaderpro.com/pdf-master-mac-download")
  259. }
  260. @objc class func openPurchaseProductWebsite() {
  261. KMTools.openURL(urlString: kKMPurchaseProductURLString)
  262. }
  263. // 意见反馈
  264. @objc class func feekback() {
  265. let (major, minor, bugFix) = KMTools.getSystemVersion()
  266. let versionInfoString = "\(KMTools.getRawSystemInfo()) - \(major).\(minor).\(bugFix)"
  267. let appVersion = KMTools.getAppVersion()
  268. let appName = KMTools.getAppName()
  269. let subjects = "\(appName) - \(appVersion);\(NSLocalizedString("Propose a New Feature", comment: ""));\(versionInfoString)"
  270. // MARK: -
  271. // MARK TODO: 邮箱域名需要替换
  272. let email = "support@pdfreaderpro.com"
  273. // MARK: -
  274. // MARK TODO: 邮箱域名需要替换
  275. KMMailHelper.newEmail(withContacts: email, andSubjects: subjects)
  276. }
  277. @objc class func getRawSystemInfo() -> String {
  278. let info = GBDeviceInfo.deviceInfo().rawSystemInfoString
  279. if (info == nil) {
  280. return ""
  281. }
  282. return info!
  283. }
  284. @objc class func getAppName() -> String {
  285. #if VERSION_PRO
  286. return "PDF Master Pro"
  287. #endif
  288. return "PDF Readre Pro"
  289. }
  290. @objc class func pageRangeTypeString(pageRange: KMPageRange) -> String {
  291. switch pageRange {
  292. case .all:
  293. return NSLocalizedString("All Pages", comment: "")
  294. case .current:
  295. return NSLocalizedString("Current Page", comment: "")
  296. case .odd:
  297. return NSLocalizedString("Odd Pages", comment: "")
  298. case .even:
  299. return NSLocalizedString("Even Pages", comment: "")
  300. case .custom:
  301. return NSLocalizedString("Customize", comment: "")
  302. case .horizontal:
  303. return NSLocalizedString("Horizontal Pages", comment: "")
  304. case .vertical:
  305. return NSLocalizedString("Vertical Pages", comment: "")
  306. }
  307. }
  308. @objc class func pageRangePlaceholderString() -> String {
  309. return NSLocalizedString("e.g. 1,3-5,10", comment: "")
  310. }
  311. @objc class func saveWatermarkDocumentToTemp(document: CPDFDocument, secureOptions: [CPDFDocumentWriteOption : Any]? = nil, removePWD: Bool = false) -> URL? {
  312. // 将文档存入临时目录
  313. if let data = self.getTempFloderPath(), !FileManager.default.fileExists(atPath: data) {
  314. try?FileManager.default.createDirectory(atPath: data, withIntermediateDirectories: false)
  315. }
  316. guard let filePath = self.getTempFloderPath()?.stringByAppendingPathComponent("temp_saveDocumentFor_temp.pdf") else {
  317. return nil
  318. }
  319. // 清除临时数据
  320. if (FileManager.default.fileExists(atPath: filePath)) {
  321. try?FileManager.default.removeItem(atPath: filePath)
  322. }
  323. return self.saveWatermarkDocument(document: document, to: URL(fileURLWithPath: filePath), secureOptions: secureOptions, removePWD: removePWD)
  324. }
  325. @objc class func saveWatermarkDocument(document: CPDFDocument, to url: URL, secureOptions: [CPDFDocumentWriteOption : Any]? = nil, documentAttribute: [CPDFDocumentAttribute : Any]? = nil, removePWD: Bool = false) -> URL? {
  326. guard let _document = self._saveDocumentForWatermark(document: document) else {
  327. return nil
  328. }
  329. // 保存文档
  330. if let data = secureOptions, !data.isEmpty {
  331. _document.setDocumentAttributes(documentAttribute)
  332. _document.write(to: url, withOptions: data)
  333. } else if (removePWD) {
  334. _document.writeDecrypt(to: url)
  335. } else {
  336. _document.write(to: url)
  337. }
  338. // 清除临时数据
  339. if let _fileUrl = _document.documentURL, FileManager.default.fileExists(atPath: _fileUrl.path) {
  340. try?FileManager.default.removeItem(atPath: _fileUrl.path)
  341. }
  342. return url
  343. }
  344. @objc class func saveWatermarkDocumentForCompress(document: CPDFDocument, to url: URL, imageQuality: Int) -> URL? {
  345. guard let _document = self._saveDocumentForWatermark(document: document) else {
  346. return nil
  347. }
  348. // _document.write(to: _document.documentURL)
  349. // 保存文档
  350. let result = _document.writeOptimize(to: url, withOptions: [.imageQualityOption : imageQuality])
  351. // 清除临时数据
  352. if let _fileUrl = _document.documentURL, FileManager.default.fileExists(atPath: _fileUrl.path) {
  353. try?FileManager.default.removeItem(atPath: _fileUrl.path)
  354. }
  355. if (result) {
  356. return url
  357. }
  358. return nil
  359. }
  360. @objc class func saveWatermarkDocumentForFlatten(document: CPDFDocument, to url: URL) -> URL? {
  361. guard let _document = self._saveDocumentForWatermark(document: document) else {
  362. return nil
  363. }
  364. // 保存文档
  365. let result = _document.writeFlatten(to: url)
  366. // 清除临时数据
  367. if let _fileUrl = _document.documentURL, FileManager.default.fileExists(atPath: _fileUrl.path) {
  368. try?FileManager.default.removeItem(atPath: _fileUrl.path)
  369. }
  370. if (result) {
  371. return url
  372. }
  373. return nil
  374. }
  375. @objc class func saveDocumentToTemp(document: CPDFDocument, fileID: String, needUnlock: Bool = true) -> URL? {
  376. // 将文档存入临时目录
  377. if let data = self.getTempFloderPath(), !FileManager.default.fileExists(atPath: data) {
  378. if let rootPath = self.getTempRootPath(), !FileManager.default.fileExists(atPath: rootPath) {
  379. try?FileManager.default.createDirectory(atPath: rootPath, withIntermediateDirectories: false)
  380. }
  381. try?FileManager.default.createDirectory(atPath: data, withIntermediateDirectories: false)
  382. }
  383. guard let filePath = self.getTempFloderPath()?.stringByAppendingPathComponent("temp_saveDocumentFor\(fileID).pdf") else {
  384. return nil
  385. }
  386. // 清除临时数据
  387. if (FileManager.default.fileExists(atPath: filePath)) {
  388. try?FileManager.default.removeItem(atPath: filePath)
  389. }
  390. document.write(toFile: filePath)
  391. if (!FileManager.default.fileExists(atPath: filePath)) {
  392. return nil
  393. }
  394. guard let _document = CPDFDocument(url: URL(fileURLWithPath: filePath)) else {
  395. return nil
  396. }
  397. if (!needUnlock) {
  398. return _document.documentURL
  399. }
  400. // 如果加锁,则去解锁
  401. if let pwd = document.password, !pwd.isEmpty, _document.isLocked {
  402. _document.unlock(withPassword: document.password)
  403. }
  404. if (_document.isLocked) {
  405. return nil
  406. }
  407. return _document.documentURL
  408. }
  409. @objc class func trackEvent(type: KMSubscribeWaterMarkType) -> Void {
  410. if (type == .stamp) {
  411. KMAnalytics.trackEvent(eventName: "PDFMaster_Subscribe_Stamp", parameters: nil, appTarget: .all)
  412. } else if (type == .link) {
  413. KMAnalytics.trackEvent(eventName: "PDFMaster_Subscribe_Link", parameters: nil, appTarget: .all)
  414. } else if (type == .sign) {
  415. KMAnalytics.trackEvent(eventName: "PDFMaster_Subscribe_Sign", parameters: nil, appTarget: .all)
  416. } else if (type == .editText) {
  417. KMAnalytics.trackEvent(eventName: "PDFMaster_Subscribe_EditText", parameters: nil, appTarget: .all)
  418. } else if (type == .editImage) {
  419. KMAnalytics.trackEvent(eventName: "PDFMaster_Subscribe_EditImage", parameters: nil, appTarget: .all)
  420. } else if (type == .insert) {
  421. KMAnalytics.trackEvent(eventName: "PDFMaster_Subscribe_Insert", parameters: nil, appTarget: .all)
  422. } else if (type == .extract) {
  423. KMAnalytics.trackEvent(eventName: "PDFMaster_Subscribe_Extract", parameters: nil, appTarget: .all)
  424. } else if (type == .replace) {
  425. KMAnalytics.trackEvent(eventName: "PDFMaster_Subscribe_Replace", parameters: nil, appTarget: .all)
  426. } else if (type == .split) {
  427. KMAnalytics.trackEvent(eventName: "PDFMaster_Subscribe_Split", parameters: nil, appTarget: .all)
  428. } else if (type == .delete) {
  429. KMAnalytics.trackEvent(eventName: "PDFMaster_Subscribe_Delete", parameters: nil, appTarget: .all)
  430. } else if (type == .rotate) {
  431. KMAnalytics.trackEvent(eventName: "PDFMaster_Subscribe_Rotate", parameters: nil, appTarget: .all)
  432. } else if (type == .copy) {
  433. KMAnalytics.trackEvent(eventName: "PDFMaster_Subscribe_Copy", parameters: nil, appTarget: .all)
  434. } else if (type == .toWord) {
  435. KMAnalytics.trackEvent(eventName: "PDFMaster_Subscribe_ToWord", parameters: nil, appTarget: .all)
  436. } else if (type == .toExcel) {
  437. KMAnalytics.trackEvent(eventName: "PDFMaster_Subscribe_ToExcel", parameters: nil, appTarget: .all)
  438. } else if (type == .toPPT) {
  439. KMAnalytics.trackEvent(eventName: "PDFMaster_Subscribe_ToPPT", parameters: nil, appTarget: .all)
  440. } else if (type == .toRTF) {
  441. KMAnalytics.trackEvent(eventName: "PDFMaster_Subscribe_ToRTF", parameters: nil, appTarget: .all)
  442. } else if (type == .toCSV) {
  443. KMAnalytics.trackEvent(eventName: "PDFMaster_Subscribe_ToCSV", parameters: nil, appTarget: .all)
  444. } else if (type == .toHTML) {
  445. KMAnalytics.trackEvent(eventName: "PDFMaster_Subscribe_ToHTML", parameters: nil, appTarget: .all)
  446. } else if (type == .toText) {
  447. KMAnalytics.trackEvent(eventName: "PDFMaster_Subscribe_ToText", parameters: nil, appTarget: .all)
  448. } else if (type == .toImage) {
  449. KMAnalytics.trackEvent(eventName: "PDFMaster_Subscribe_ToImage", parameters: nil, appTarget: .all)
  450. } else if (type == .compress) {
  451. KMAnalytics.trackEvent(eventName: "PDFMaster_Subscribe_Compress", parameters: nil, appTarget: .all)
  452. } else if (type == .merge) {
  453. KMAnalytics.trackEvent(eventName: "PDFMaster_Subscribe_Merge", parameters: nil, appTarget: .all)
  454. } else if (type == .setPassword) {
  455. KMAnalytics.trackEvent(eventName: "PDFMaster_Subscribe_SetPassword", parameters: nil, appTarget: .all)
  456. } else if (type == .removePassword) {
  457. KMAnalytics.trackEvent(eventName: "PDFMaster_Subscribe_RemovePassword", parameters: nil, appTarget: .all)
  458. } else if (type == .crop) {
  459. KMAnalytics.trackEvent(eventName: "PDFMaster_Subscribe_Crop", parameters: nil, appTarget: .all)
  460. } else if (type == .aiTranslate) {
  461. KMAnalytics.trackEvent(eventName: "PDFMaster_Subscribe_AITranslate", parameters: nil, appTarget: .all)
  462. } else if (type == .aiRewrite) {
  463. KMAnalytics.trackEvent(eventName: "PDFMaster_Subscribe_AIRewrite", parameters: nil, appTarget: .all)
  464. } else if (type == .aiCorrect) {
  465. KMAnalytics.trackEvent(eventName: "PDFMaster_Subscribe_AICorrect", parameters: nil, appTarget: .all)
  466. }
  467. }
  468. // MARK: - Private Methods
  469. @objc fileprivate class func _documentAddWatermark(document: CPDFDocument) -> CPDFDocument? {
  470. // 添加水印
  471. let watermark = CPDFWatermark(document: document, type: .image)
  472. watermark?.image = NSImage(named: "KMImageNameWatermark")
  473. watermark?.horizontalPosition = .left
  474. watermark?.verticalPosition = .top
  475. watermark?.scale = 0.5
  476. document.addWatermark(watermark)
  477. // 添加 link注释
  478. var watermarkAnnoBounds = NSMakeRect(0, 0, 120, 32)
  479. for i in 0 ..< document.pageCount {
  480. guard let page = document.page(at: i) else {
  481. continue
  482. }
  483. // 水印注释 frame
  484. watermarkAnnoBounds.origin.y = page.bounds.size.height-watermarkAnnoBounds.size.height
  485. // 找到需要删除的水印注释(之前添加)
  486. var flagAnnos: [CPDFAnnotation] = []
  487. for anno in page.annotations {
  488. if let anno_link = anno as? CPDFLinkAnnotation, anno_link.url() == kKMPurchaseProductURLString, anno_link.bounds.equalTo(watermarkAnnoBounds) {
  489. flagAnnos.append(anno_link)
  490. }
  491. }
  492. // 删除之前的水印注释
  493. for anno in flagAnnos {
  494. page.removeAnnotation(anno)
  495. }
  496. // 新增新的水印注释
  497. let anno = CPDFLinkAnnotation(document: document)
  498. anno?.bounds = watermarkAnnoBounds
  499. anno?.setURL(kKMPurchaseProductURLString)
  500. page.addAnnotation(anno)
  501. }
  502. return document
  503. }
  504. @objc fileprivate class func _saveDocumentForWatermark(document: CPDFDocument) -> CPDFDocument? {
  505. // 将文档存入临时目录
  506. guard let _fileUrl = self.saveDocumentToTemp(document: document, fileID: "Watermark") else {
  507. return nil
  508. }
  509. guard let _document = CPDFDocument(url: _fileUrl) else {
  510. return nil
  511. }
  512. // 如果加锁,则去解锁
  513. if let pwd = document.password, !pwd.isEmpty, _document.isLocked {
  514. _document.unlock(withPassword: pwd)
  515. }
  516. // 添加水印
  517. return self._documentAddWatermark(document: _document)
  518. }
  519. }