KMTools.swift 24 KB

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