KMTools.swift 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602
  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. #if VERSION_PRO
  277. return "PDF Master Pro"
  278. #endif
  279. return "PDF Readre Pro"
  280. }
  281. @objc class func pageRangeTypeString(pageRange: KMPageRange) -> String {
  282. switch pageRange {
  283. case .all:
  284. return NSLocalizedString("All Pages", comment: "")
  285. case .current:
  286. return NSLocalizedString("Current Page", comment: "")
  287. case .odd:
  288. return NSLocalizedString("Odd Pages", comment: "")
  289. case .even:
  290. return NSLocalizedString("Even Pages", comment: "")
  291. case .custom:
  292. return NSLocalizedString("Customize", comment: "")
  293. case .horizontal:
  294. return NSLocalizedString("Horizontal Pages", comment: "")
  295. case .vertical:
  296. return NSLocalizedString("Vertical Pages", comment: "")
  297. }
  298. }
  299. @objc class func pageRangePlaceholderString() -> String {
  300. return NSLocalizedString("e.g. 1,3-5,10", comment: "")
  301. }
  302. @objc class func saveWatermarkDocumentToTemp(document: CPDFDocument, secureOptions: [CPDFDocumentWriteOption : Any]? = nil, removePWD: Bool = false) -> URL? {
  303. // 将文档存入临时目录
  304. if let data = self.getTempFloderPath(), !FileManager.default.fileExists(atPath: data) {
  305. try?FileManager.default.createDirectory(atPath: data, withIntermediateDirectories: false)
  306. }
  307. guard let filePath = self.getTempFloderPath()?.stringByAppendingPathComponent("temp_saveDocumentFor_temp.pdf") else {
  308. return nil
  309. }
  310. // 清除临时数据
  311. if (FileManager.default.fileExists(atPath: filePath)) {
  312. try?FileManager.default.removeItem(atPath: filePath)
  313. }
  314. return self.saveWatermarkDocument(document: document, to: URL(fileURLWithPath: filePath), secureOptions: secureOptions, removePWD: removePWD)
  315. }
  316. @objc class func saveWatermarkDocument(document: CPDFDocument, to url: URL, secureOptions: [CPDFDocumentWriteOption : Any]? = nil, documentAttribute: [CPDFDocumentAttribute : Any]? = nil, removePWD: Bool = false) -> URL? {
  317. guard let _document = self._saveDocumentForWatermark(document: document) else {
  318. return nil
  319. }
  320. // 保存文档
  321. if let data = secureOptions, !data.isEmpty {
  322. _document.setDocumentAttributes(documentAttribute)
  323. _document.write(to: url, withOptions: data)
  324. } else if (removePWD) {
  325. _document.writeDecrypt(to: url)
  326. } else {
  327. _document.write(to: url)
  328. }
  329. // 清除临时数据
  330. if let _fileUrl = _document.documentURL, FileManager.default.fileExists(atPath: _fileUrl.path) {
  331. try?FileManager.default.removeItem(atPath: _fileUrl.path)
  332. }
  333. return url
  334. }
  335. @objc class func saveWatermarkDocumentForCompress(document: CPDFDocument, to url: URL, imageQuality: Int) -> URL? {
  336. guard let _document = self._saveDocumentForWatermark(document: document) else {
  337. return nil
  338. }
  339. // _document.write(to: _document.documentURL)
  340. // 保存文档
  341. let result = _document.writeOptimize(to: url, withOptions: [.imageQualityOption : imageQuality])
  342. // 清除临时数据
  343. if let _fileUrl = _document.documentURL, FileManager.default.fileExists(atPath: _fileUrl.path) {
  344. try?FileManager.default.removeItem(atPath: _fileUrl.path)
  345. }
  346. if (result) {
  347. return url
  348. }
  349. return nil
  350. }
  351. @objc class func saveWatermarkDocumentForFlatten(document: CPDFDocument, to url: URL) -> URL? {
  352. guard let _document = self._saveDocumentForWatermark(document: document) else {
  353. return nil
  354. }
  355. // 保存文档
  356. let result = _document.writeFlatten(to: url)
  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 saveDocumentToTemp(document: CPDFDocument, fileID: String, needUnlock: Bool = true) -> URL? {
  367. // 将文档存入临时目录
  368. if let data = self.getTempFloderPath(), !FileManager.default.fileExists(atPath: data) {
  369. try?FileManager.default.createDirectory(atPath: data, withIntermediateDirectories: false)
  370. }
  371. guard let filePath = self.getTempFloderPath()?.stringByAppendingPathComponent("temp_saveDocumentFor\(fileID).pdf") else {
  372. return nil
  373. }
  374. // 清除临时数据
  375. if (FileManager.default.fileExists(atPath: filePath)) {
  376. try?FileManager.default.removeItem(atPath: filePath)
  377. }
  378. document.write(toFile: filePath)
  379. if (!FileManager.default.fileExists(atPath: filePath)) {
  380. return nil
  381. }
  382. guard let _document = CPDFDocument(url: URL(fileURLWithPath: filePath)) else {
  383. return nil
  384. }
  385. if (!needUnlock) {
  386. return _document.documentURL
  387. }
  388. // 如果加锁,则去解锁
  389. if let pwd = document.password, !pwd.isEmpty, _document.isLocked {
  390. _document.unlock(withPassword: document.password)
  391. }
  392. if (_document.isLocked) {
  393. return nil
  394. }
  395. return _document.documentURL
  396. }
  397. @objc class func trackEvent(type: KMSubscribeWaterMarkType) -> Void {
  398. if (type == .stamp) {
  399. KMAnalytics.trackEvent(eventName: "PDFMaster_Subscribe_Stamp", parameters: nil, appTarget: .all)
  400. } else if (type == .link) {
  401. KMAnalytics.trackEvent(eventName: "PDFMaster_Subscribe_Link", parameters: nil, appTarget: .all)
  402. } else if (type == .sign) {
  403. KMAnalytics.trackEvent(eventName: "PDFMaster_Subscribe_Sign", parameters: nil, appTarget: .all)
  404. } else if (type == .editText) {
  405. KMAnalytics.trackEvent(eventName: "PDFMaster_Subscribe_EditText", parameters: nil, appTarget: .all)
  406. } else if (type == .editImage) {
  407. KMAnalytics.trackEvent(eventName: "PDFMaster_Subscribe_EditImage", parameters: nil, appTarget: .all)
  408. } else if (type == .insert) {
  409. KMAnalytics.trackEvent(eventName: "PDFMaster_Subscribe_Insert", parameters: nil, appTarget: .all)
  410. } else if (type == .extract) {
  411. KMAnalytics.trackEvent(eventName: "PDFMaster_Subscribe_Extract", parameters: nil, appTarget: .all)
  412. } else if (type == .replace) {
  413. KMAnalytics.trackEvent(eventName: "PDFMaster_Subscribe_Replace", parameters: nil, appTarget: .all)
  414. } else if (type == .split) {
  415. KMAnalytics.trackEvent(eventName: "PDFMaster_Subscribe_Split", parameters: nil, appTarget: .all)
  416. } else if (type == .delete) {
  417. KMAnalytics.trackEvent(eventName: "PDFMaster_Subscribe_Delete", parameters: nil, appTarget: .all)
  418. } else if (type == .rotate) {
  419. KMAnalytics.trackEvent(eventName: "PDFMaster_Subscribe_Rotate", parameters: nil, appTarget: .all)
  420. } else if (type == .copy) {
  421. KMAnalytics.trackEvent(eventName: "PDFMaster_Subscribe_Copy", parameters: nil, appTarget: .all)
  422. } else if (type == .toWord) {
  423. KMAnalytics.trackEvent(eventName: "PDFMaster_Subscribe_ToWord", parameters: nil, appTarget: .all)
  424. } else if (type == .toExcel) {
  425. KMAnalytics.trackEvent(eventName: "PDFMaster_Subscribe_ToExcel", parameters: nil, appTarget: .all)
  426. } else if (type == .toPPT) {
  427. KMAnalytics.trackEvent(eventName: "PDFMaster_Subscribe_ToPPT", parameters: nil, appTarget: .all)
  428. } else if (type == .toRTF) {
  429. KMAnalytics.trackEvent(eventName: "PDFMaster_Subscribe_ToRTF", parameters: nil, appTarget: .all)
  430. } else if (type == .toCSV) {
  431. KMAnalytics.trackEvent(eventName: "PDFMaster_Subscribe_ToCSV", parameters: nil, appTarget: .all)
  432. } else if (type == .toHTML) {
  433. KMAnalytics.trackEvent(eventName: "PDFMaster_Subscribe_ToHTML", parameters: nil, appTarget: .all)
  434. } else if (type == .toText) {
  435. KMAnalytics.trackEvent(eventName: "PDFMaster_Subscribe_ToText", parameters: nil, appTarget: .all)
  436. } else if (type == .toImage) {
  437. KMAnalytics.trackEvent(eventName: "PDFMaster_Subscribe_ToImage", parameters: nil, appTarget: .all)
  438. } else if (type == .compress) {
  439. KMAnalytics.trackEvent(eventName: "PDFMaster_Subscribe_Compress", parameters: nil, appTarget: .all)
  440. } else if (type == .merge) {
  441. KMAnalytics.trackEvent(eventName: "PDFMaster_Subscribe_Merge", parameters: nil, appTarget: .all)
  442. } else if (type == .setPassword) {
  443. KMAnalytics.trackEvent(eventName: "PDFMaster_Subscribe_SetPassword", parameters: nil, appTarget: .all)
  444. } else if (type == .removePassword) {
  445. KMAnalytics.trackEvent(eventName: "PDFMaster_Subscribe_RemovePassword", parameters: nil, appTarget: .all)
  446. } else if (type == .crop) {
  447. KMAnalytics.trackEvent(eventName: "PDFMaster_Subscribe_Crop", parameters: nil, appTarget: .all)
  448. } else if (type == .aiTranslate) {
  449. KMAnalytics.trackEvent(eventName: "PDFMaster_Subscribe_AITranslate", parameters: nil, appTarget: .all)
  450. } else if (type == .aiRewrite) {
  451. KMAnalytics.trackEvent(eventName: "PDFMaster_Subscribe_AIRewrite", parameters: nil, appTarget: .all)
  452. } else if (type == .aiCorrect) {
  453. KMAnalytics.trackEvent(eventName: "PDFMaster_Subscribe_AICorrect", parameters: nil, appTarget: .all)
  454. }
  455. }
  456. // MARK: - Private Methods
  457. @objc fileprivate class func _documentAddWatermark(document: CPDFDocument) -> CPDFDocument? {
  458. // 添加水印
  459. let watermark = CPDFWatermark(document: document, type: .image)
  460. watermark?.image = NSImage(named: "KMImageNameWatermark")
  461. watermark?.horizontalPosition = .left
  462. watermark?.verticalPosition = .top
  463. watermark?.scale = 0.5
  464. document.addWatermark(watermark)
  465. // 添加 link注释
  466. var watermarkAnnoBounds = NSMakeRect(0, 0, 120, 32)
  467. for i in 0 ..< document.pageCount {
  468. guard let page = document.page(at: i) else {
  469. continue
  470. }
  471. // 水印注释 frame
  472. watermarkAnnoBounds.origin.y = page.bounds.size.height-watermarkAnnoBounds.size.height
  473. // 找到需要删除的水印注释(之前添加)
  474. var flagAnnos: [CPDFAnnotation] = []
  475. for anno in page.annotations {
  476. if let anno_link = anno as? CPDFLinkAnnotation, anno_link.url() == kKMPurchaseProductURLString, anno_link.bounds.equalTo(watermarkAnnoBounds) {
  477. flagAnnos.append(anno_link)
  478. }
  479. }
  480. // 删除之前的水印注释
  481. for anno in flagAnnos {
  482. page.removeAnnotation(anno)
  483. }
  484. // 新增新的水印注释
  485. let anno = CPDFLinkAnnotation(document: document)
  486. anno?.bounds = watermarkAnnoBounds
  487. anno?.setURL(kKMPurchaseProductURLString)
  488. page.addAnnotation(anno)
  489. }
  490. return document
  491. }
  492. @objc fileprivate class func _saveDocumentForWatermark(document: CPDFDocument) -> CPDFDocument? {
  493. // 将文档存入临时目录
  494. guard let _fileUrl = self.saveDocumentToTemp(document: document, fileID: "Watermark") else {
  495. return nil
  496. }
  497. guard let _document = CPDFDocument(url: _fileUrl) else {
  498. return nil
  499. }
  500. // 如果加锁,则去解锁
  501. if let pwd = document.password, !pwd.isEmpty, _document.isLocked {
  502. _document.unlock(withPassword: pwd)
  503. }
  504. // 添加水印
  505. return self._documentAddWatermark(document: _document)
  506. }
  507. }