KMTools.swift 24 KB

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