KMTools.swift 24 KB

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