KMTools.swift 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766
  1. //
  2. // KMTools.swift
  3. // PDF Reader Pro
  4. //
  5. // Created by tangchao on 2023/3/7.
  6. //
  7. import Cocoa
  8. @objc class KMTools: NSObject {
  9. // MARK: - 获取已打开的文件
  10. static let defaultManager: KMTools = {
  11. let manager = KMTools()
  12. return manager
  13. }()
  14. var isTabbingWin = false //多页签提示页是否展示中
  15. @objc class func getOpenDocumentURLs() -> [URL] {
  16. var files:[URL] = []
  17. for window in NSApp.windows {
  18. if ((window.windowController is KMBrowserWindowController) == false) {
  19. continue
  20. }
  21. let controller: KMBrowserWindowController = window.windowController as! KMBrowserWindowController
  22. let model = controller.browser?.tabStripModel
  23. guard let count = model?.count() else {
  24. continue
  25. }
  26. if (count <= 0) {
  27. continue
  28. }
  29. for i in 0 ..< count {
  30. let document = model?.tabContents(at: Int32(i))
  31. // if (document?.windowControllers == nil || document?.windowControllers.count == 0) {
  32. // continue
  33. // }
  34. if (document?.fileURL == nil) {
  35. continue
  36. }
  37. if (document?.isHome == nil || document!.isHome) {
  38. continue
  39. }
  40. files.append((document?.fileURL)!)
  41. }
  42. }
  43. return files
  44. }
  45. // MARK: - 无法区分 [权限+开启] [开启] 这两种情况 请不要使用
  46. private class func isDocumentHasPermissionsPassword(_ url: URL) -> Bool {
  47. let document = PDFDocument(url: url)
  48. if (document == nil) {
  49. return false
  50. }
  51. if (document?.permissionsStatus == .user) {
  52. return true
  53. }
  54. // document?.permissionsStatus == .none
  55. if (document!.isLocked == false) { // 没有加锁
  56. return false
  57. }
  58. // 已加锁 [权限+开启] [开启]
  59. if (KMTools.hasPermissionsLimit(document!)) { // 有权限限制
  60. return true
  61. }
  62. return false
  63. }
  64. // MARK: - 暂时只处理了复制和打印两项(后续项目需求有新增时,可以再此方法里扩展)
  65. @objc class func hasPermissionsLimit(_ document: PDFDocument) -> Bool {
  66. if (document.allowsCopying == false) {
  67. return true
  68. }
  69. if (document.allowsPrinting == false) {
  70. return true
  71. }
  72. return false
  73. }
  74. // MARK: - 打开网页
  75. @objc class func openURL(url: URL?) {
  76. guard let _url = url else {
  77. KMPrint("url invalid.")
  78. return
  79. }
  80. NSWorkspace.shared.open(_url)
  81. }
  82. @objc class func openURL(urlString: String?) {
  83. guard let _urlString = urlString else {
  84. KMPrint("url invalid.")
  85. return
  86. }
  87. KMTools.openURL(url: URL(string: _urlString))
  88. }
  89. // MARK: - 查看文件
  90. @objc class func viewFile(at filepath: String) {
  91. let ws = NSWorkspace.shared
  92. let url = URL(fileURLWithPath: filepath)
  93. ws.activateFileViewerSelecting([url])
  94. }
  95. // MARK: - 获取 App 版本号
  96. @objc class func getAppVersion() -> String {
  97. let infoDictionary = Bundle.main.infoDictionary
  98. if (infoDictionary == nil) {
  99. return "1.0.0"
  100. }
  101. var version = infoDictionary!["CFBundleShortVersionString"]
  102. if (version != nil && (version is String) && (version as! String).isEmpty == false) {
  103. return version as! String
  104. }
  105. version = infoDictionary!["CFBundleVersion"]
  106. if (version != nil && (version is String) && (version as! String).isEmpty == false) {
  107. return version as! String
  108. }
  109. return "1.0.0"
  110. }
  111. class func getSystemVersion() -> (Int, Int, Int) {
  112. let versionInfo = ProcessInfo.processInfo.operatingSystemVersion
  113. return (versionInfo.majorVersion, versionInfo.minorVersion, versionInfo.patchVersion)
  114. }
  115. @objc class func isDefaultPDFReader() -> Bool {
  116. let app = LSCopyDefaultRoleHandlerForContentType("pdf" as CFString, LSRolesMask.all)?.takeUnretainedValue()
  117. if (app == nil) {
  118. return false
  119. }
  120. return (app! as String) == Bundle.main.bundleIdentifier!
  121. }
  122. @objc class func setDefaultPDFReader(_ isOrNo: Bool) -> Bool {
  123. var bid = "com.apple.Preview"
  124. if (isOrNo) {
  125. bid = Bundle.main.bundleIdentifier!
  126. }
  127. let status: OSStatus = LSSetDefaultRoleHandlerForContentType(KMTools.UTIforFileExtension("pdf") as CFString, LSRolesMask.all, bid as CFString)
  128. if (status == 0) {
  129. return true
  130. }
  131. return false
  132. }
  133. @objc class func UTIforFileExtension(_ exn: String) -> String {
  134. return (UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, exn as CFString, nil)?.takeUnretainedValue())! as String
  135. }
  136. // MARK: - 是否全屏
  137. @objc class func isFullScreen(_ window: NSWindow) -> Bool {
  138. return window.styleMask.contains(.fullScreen)
  139. }
  140. // MARK: - 文件类型
  141. static let imageExtensions = ["jpg","cur","bmp","jpeg","gif","png","tiff","tif",/*@"pic",*/"ico","icns","tga","psd","eps","hdr","jp2","jpc","pict","sgi","heic"]
  142. static let pdfExtensions = ["pdf"]
  143. static let officeExtensions = ["doc", "docx", "xls", "xlsx", "ppt", "pptx"]
  144. @objc class func isImageType(_ exn: String) -> Bool {
  145. return KMTools.imageExtensions.contains(exn.lowercased())
  146. }
  147. @objc class func isPDFType(_ exn: String) -> Bool {
  148. return KMTools.pdfExtensions.contains(exn.lowercased())
  149. }
  150. @objc class func isOfficeType(_ exn: String) -> Bool {
  151. return KMTools.officeExtensions.contains(exn.lowercased())
  152. }
  153. @objc class func getUniqueFilePath(filePath: String) -> String {
  154. var isDirectory: ObjCBool = false
  155. var uniqueFilePath = filePath
  156. let fileManager = FileManager.default
  157. fileManager.fileExists(atPath: uniqueFilePath, isDirectory: &isDirectory)
  158. var i = 0
  159. if (isDirectory.boolValue) {
  160. while fileManager.fileExists(atPath: uniqueFilePath) {
  161. i += 1
  162. uniqueFilePath = "\(filePath)(\(i))"
  163. }
  164. } else {
  165. let fileURL = URL(fileURLWithPath: filePath)
  166. let path = fileURL.deletingPathExtension().path
  167. while fileManager.fileExists(atPath: uniqueFilePath) {
  168. i += 1
  169. uniqueFilePath = "\(path)(\(i).\(fileURL.pathExtension)"
  170. }
  171. }
  172. return uniqueFilePath
  173. }
  174. @objc class func getTempFloderPath() -> String? {
  175. return self.getTempRootPath()?.stringByAppendingPathComponent("KMTemp")
  176. }
  177. @objc class func getTempRootPath() -> String? {
  178. return NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.applicationSupportDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).last?.stringByAppendingPathComponent(Bundle.main.bundleIdentifier!)
  179. }
  180. // MARK: - Document isDocumentEdited
  181. @objc class func setDocumentEditedState(window: NSWindow) {
  182. guard let _document = NSDocumentController.shared.document(for: window) else {
  183. return
  184. }
  185. self.setDocumentEditedState(document: _document)
  186. }
  187. @objc class func setDocumentEditedState(url: URL) {
  188. guard let _document = NSDocumentController.shared.document(for: url) else {
  189. return
  190. }
  191. self.setDocumentEditedState(document: _document)
  192. }
  193. @objc class func setDocumentEditedState(document: NSDocument) {
  194. km_synchronized(document) {
  195. document.updateChangeCount(.changeDone)
  196. }
  197. }
  198. @objc class func clearDocumentEditedState(window: NSWindow) {
  199. guard let _document = NSDocumentController.shared.document(for: window) else {
  200. return
  201. }
  202. self.clearDocumentEditedState(document: _document)
  203. }
  204. @objc class func clearDocumentEditedState(url: URL) {
  205. guard let _document = NSDocumentController.shared.document(for: url) else {
  206. return
  207. }
  208. self.clearDocumentEditedState(document: _document)
  209. }
  210. @objc class func clearDocumentEditedState(document: NSDocument) {
  211. km_synchronized(document) {
  212. document.updateChangeCount(.changeCleared)
  213. }
  214. }
  215. }
  216. // MARK: - PDFReaderPro
  217. let kKMPurchaseProductURLString = "https://www.pdfreaderpro.com/store"
  218. extension KMTools {
  219. // 打开 [快速教学]
  220. @objc class func openQuickStartStudy() {
  221. // MARK: -
  222. // MARK: 内嵌文档需要替换
  223. var fileName = "Quick Start Guide"
  224. let fileType = "pdf"
  225. let path = Bundle.main.path(forResource: fileName, ofType: fileType)
  226. if (path == nil || FileManager.default.fileExists(atPath: path!) == false) {
  227. KMTools.openURL(url: URL(string: "https://www.pdfreaderpro.com/help"))
  228. return
  229. }
  230. let version = KMTools.getAppVersion()
  231. fileName.append(" v\(version).\(fileType)")
  232. let folderPath = NSSearchPathForDirectoriesInDomains(.applicationSupportDirectory, .userDomainMask, true).last?.appending("/\(Bundle.main.bundleIdentifier!)")
  233. if (FileManager.default.fileExists(atPath: folderPath!) == false) {
  234. try?FileManager.default.createDirectory(atPath: folderPath!, withIntermediateDirectories: false)
  235. }
  236. let toPath = "\(folderPath!)/\(fileName)"
  237. if (FileManager.default.fileExists(atPath: toPath)) {
  238. try?FileManager.default.removeItem(atPath: toPath)
  239. }
  240. try?FileManager.default.copyItem(atPath: path!, toPath: toPath)
  241. NSDocumentController.shared.km_safe_openDocument(withContentsOf: URL(fileURLWithPath: toPath), display: true) { _, _, _ in
  242. }
  243. }
  244. // 打开 [FAQ] 网站
  245. @objc class func openFAQWebsite() {
  246. var tStrUrl: String?
  247. #if VERSION_FREE
  248. #if VERSION_DMG
  249. tStrUrl = "https://www.pdfreaderpro.com/help?utm_source=MacAppDmg&utm_campaign=HelpLink&utm_medium=PdfHelp"
  250. #else
  251. tStrUrl = "https://www.pdfreaderpro.com/help?utm_source=MacAppLite&utm_campaign=HelpLink&utm_medium=PdfHelp"
  252. #endif
  253. #else
  254. tStrUrl = "https://www.pdfreaderpro.com/help?utm_source=MacApp&utm_campaign=HelpLink&utm_medium=PdfHelp"
  255. #endif
  256. KMTools.openURL(urlString: tStrUrl)
  257. }
  258. // 打开 [更多产品] 网站
  259. @objc class func openMoreProductWebsite() {
  260. var tStrUrl: String?
  261. if KMKdanRemoteConfig.remoteConfig().showHelp_More_RecommendLink() {
  262. #if VERSION_FREE
  263. tStrUrl = "https://www.pdfreaderpro.com/product?utm_source=MacAppLite&utm_campaign=ProductLink&utm_medium=PdfProduct"
  264. #else
  265. tStrUrl = "https://www.pdfreaderpro.com/product?utm_source=MacApp&utm_campaign=ProductLink&utm_medium=PdfProduct"
  266. #endif
  267. } else {
  268. tStrUrl = "https://apps.apple.com/developer/pdf-technologies-inc/id1263126485"
  269. }
  270. #if VERSION_DMG
  271. tStrUrl = "https://www.pdfreaderpro.com/product?utm_source=MacAppDmg&utm_campaign=ProductLink&utm_medium=PdfProduct"
  272. #endif
  273. KMTools.openURL(urlString: tStrUrl)
  274. }
  275. // 打开 [免费 PDF 模板] 网站
  276. @objc class func openFreePDFTemplatesWebsite() {
  277. var tStrUrl: String?
  278. #if VERSION_FREE
  279. #if VERSION_DMG
  280. tStrUrl = "https://www.pdfreaderpro.com/templates?utm_source=MacAppDmg&utm_campaign=TemplatesLink&utm_medium=PdfTemplates"
  281. #else
  282. tStrUrl = "https://www.pdfreaderpro.com/templates?utm_source=MacAppLite&utm_campaign=TemplatesLink&utm_medium=PdfTemplates"
  283. #endif
  284. #else
  285. tStrUrl = "https://www.pdfreaderpro.com/templates?utm_source=MacApp&utm_campaign=TemplatesLink&utm_medium=PdfTemplates"
  286. #endif
  287. KMTools.openURL(urlString: tStrUrl)
  288. }
  289. // 打开 [ComPDFKit 授权] 网站
  290. @objc class func openComPDFKitPowerWebsite() {
  291. KMTools.openURL(url: URL(string: "https://www.compdf.com?utm_source=macapp&utm_medium=pdfmac&utm_campaign=compdfkit-promp"))
  292. }
  293. // 打开 [官网 下载页] 网站
  294. // 测试环境 http://test-pdf-pro.kdan.cn:3021/pdf-master-mac-download
  295. @objc class func openDownloadDMGWebsite() {
  296. KMTools.openURL(urlString: "https://www.pdfreaderpro.com/pdf-master-mac-download")
  297. }
  298. @objc class func openPurchaseProductWebsite() {
  299. KMTools.openURL(urlString: kKMPurchaseProductURLString)
  300. }
  301. // 意见反馈
  302. @objc class func feekback() {
  303. let (major, minor, bugFix) = KMTools.getSystemVersion()
  304. let versionInfoString = "\(KMTools.getRawSystemInfo()) - \(major).\(minor).\(bugFix)"
  305. let appVersion = KMTools.getAppVersion()
  306. let appName = KMTools.getAppNameForSupportEmail()
  307. let subjects = "\(appName) - \(appVersion);\(NSLocalizedString("Feedback", comment: ""));\(versionInfoString)"
  308. let email = "support@pdfreaderpro.com"
  309. KMMailHelper.newEmail(withContacts: email, andSubjects: subjects)
  310. }
  311. //
  312. @objc class func reportBug() {
  313. let (major, minor, bugFix) = KMTools.getSystemVersion()
  314. let versionInfoString = "\(KMTools.getRawSystemInfo()) - \(major).\(minor).\(bugFix)"
  315. let appVersion = KMTools.getAppVersion()
  316. let appName = KMTools.getAppNameForSupportEmail()
  317. let subjects = "\(appName) - \(appVersion);\(NSLocalizedString("Report a Bug", comment: ""));\(versionInfoString)"
  318. let email = "support@pdfreaderpro.com"
  319. KMMailHelper.newEmail(withContacts: email, andSubjects: subjects)
  320. }
  321. //
  322. @objc class func proposeNewFeature() {
  323. let (major, minor, bugFix) = KMTools.getSystemVersion()
  324. let versionInfoString = "\(KMTools.getRawSystemInfo()) - \(major).\(minor).\(bugFix)"
  325. let appVersion = KMTools.getAppVersion()
  326. let appName = KMTools.getAppNameForSupportEmail()
  327. let subjects = "\(appName) - \(appVersion);\(NSLocalizedString("Propose a New Feature", comment: ""));\(versionInfoString)"
  328. let email = "support@pdfreaderpro.com"
  329. KMMailHelper.newEmail(withContacts: email, andSubjects: subjects)
  330. }
  331. //
  332. @objc class func reportGeneralQuestions() {
  333. let (major, minor, bugFix) = KMTools.getSystemVersion()
  334. let versionInfoString = "\(KMTools.getRawSystemInfo()) - \(major).\(minor).\(bugFix)"
  335. let appVersion = KMTools.getAppVersion()
  336. let appName = KMTools.getAppNameForSupportEmail()
  337. let subjects = "\(appName) - \(appVersion);\(NSLocalizedString("General Questions", comment: ""));\(versionInfoString)"
  338. let email = "support@pdfreaderpro.com"
  339. KMMailHelper.newEmail(withContacts: email, andSubjects: subjects)
  340. }
  341. @objc class func rateUs() {
  342. #if VERSION_FREE
  343. iRate.sharedInstance().appStoreID = 919472673
  344. #else
  345. iRate.sharedInstance().appStoreID = 825459243
  346. #endif
  347. if UserDefaults.standard.bool(forKey: "kUserHaveClickRateUsKey") == false {
  348. UserDefaults.standard.set(true, forKey: "kUserHaveClickRateUsKey")
  349. UserDefaults.standard.synchronize()
  350. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "kUserHaveClickRateUsNotification"), object: self)
  351. }
  352. iRate.sharedInstance().openRatingsPageInAppStore()
  353. }
  354. @objc class func getAppNameForSupportEmail() -> String {
  355. var tAppName = "PDF Reader Pro"
  356. #if VERSION_FREE
  357. #if VERSION_DMG
  358. #if VERSION_BETA
  359. tAppName = "PDF Reader Pro Beta"
  360. #endif
  361. // 桌机版
  362. // VerificationManager *tManager = [VerificationManager manager];
  363. // switch ([tManager status]) {
  364. // case ActivityStatusTrial:
  365. // tAppName = [tAppName stringByAppendingString:@" Trial"];
  366. // break;
  367. //
  368. // case ActivityStatusVerification:
  369. // tAppName = [tAppName stringByAppendingString:@" Verification"];
  370. // break;
  371. //
  372. // case ActivityStatusTrialExpire:
  373. // tAppName = [tAppName stringByAppendingString:@" TrialExpire"];
  374. // break;
  375. //
  376. // case ActivityStatusVerifExpire:
  377. // tAppName = [tAppName stringByAppendingString:@" VerifExpire"];
  378. // break;
  379. //
  380. // default:
  381. // break;
  382. // }
  383. if let tManager = VerificationManager.default() {
  384. let status = tManager.status
  385. if status == ActivityStatus.trial {
  386. tAppName = "\(tAppName) Trial"
  387. } else if status == ActivityStatus.verification {
  388. tAppName = "\(tAppName) Verification"
  389. } else if status == ActivityStatus.trialExpired {
  390. tAppName = "\(tAppName) TrialExpire"
  391. } else if status == ActivityStatus.verifExpire {
  392. tAppName = "\(tAppName) VerifExpire"
  393. }
  394. }
  395. #else
  396. // AppStore 免费版本
  397. tAppName = "PDF Reader Pro Lite"
  398. #endif
  399. #else
  400. // AppStore 付费版
  401. tAppName = "PDF Reader Pro Edition"
  402. #endif
  403. return tAppName
  404. }
  405. @objc class func getRawSystemInfo() -> String {
  406. let info = GBDeviceInfo.deviceInfo().rawSystemInfoString
  407. if (info == nil) {
  408. return ""
  409. }
  410. return info!
  411. }
  412. @objc class func getAppName() -> String {
  413. #if VERSION_PRO
  414. return "PDF Reader Pro"
  415. #endif
  416. return "PDF Readre Pro"
  417. }
  418. @objc class func pageRangeTypeString(pageRange: KMPageRange) -> String {
  419. switch pageRange {
  420. case .all:
  421. return NSLocalizedString("All Pages", comment: "")
  422. case .current:
  423. return NSLocalizedString("Current Page", comment: "")
  424. case .odd:
  425. return NSLocalizedString("Odd Pages", comment: "")
  426. case .even:
  427. return NSLocalizedString("Even Pages", comment: "")
  428. case .custom:
  429. return NSLocalizedString("Customize", comment: "")
  430. case .horizontal:
  431. return NSLocalizedString("Horizontal Pages", comment: "")
  432. case .vertical:
  433. return NSLocalizedString("Vertical Pages", comment: "")
  434. }
  435. }
  436. @objc class func pageRangePlaceholderString() -> String {
  437. return NSLocalizedString("e.g. 1,3-5,10", comment: "")
  438. }
  439. @objc class func saveWatermarkDocumentToTemp(document: CPDFDocument, secureOptions: [CPDFDocumentWriteOption : Any]? = nil, removePWD: Bool = false) -> URL? {
  440. // 将文档存入临时目录
  441. if let data = self.getTempFloderPath(), !FileManager.default.fileExists(atPath: data) {
  442. try?FileManager.default.createDirectory(atPath: data, withIntermediateDirectories: false)
  443. }
  444. guard let filePath = self.getTempFloderPath()?.stringByAppendingPathComponent("temp_saveDocumentFor_temp.pdf") else {
  445. return nil
  446. }
  447. // 清除临时数据
  448. if (FileManager.default.fileExists(atPath: filePath)) {
  449. try?FileManager.default.removeItem(atPath: filePath)
  450. }
  451. return self.saveWatermarkDocument(document: document, to: URL(fileURLWithPath: filePath), secureOptions: secureOptions, removePWD: removePWD)
  452. }
  453. @objc class func saveWatermarkDocument(document: CPDFDocument, to url: URL, secureOptions: [CPDFDocumentWriteOption : Any]? = nil, documentAttribute: [CPDFDocumentAttribute : Any]? = nil, removePWD: Bool = false) -> URL? {
  454. guard let _document = self._saveDocumentForWatermark(document: document) else {
  455. return nil
  456. }
  457. // 保存文档
  458. if let data = secureOptions, !data.isEmpty {
  459. _document.setDocumentAttributes(documentAttribute)
  460. _document.write(to: url, withOptions: data)
  461. } else if (removePWD) {
  462. _document.writeDecrypt(to: url)
  463. } else {
  464. _document.write(to: url)
  465. }
  466. // 清除临时数据
  467. if let _fileUrl = _document.documentURL, FileManager.default.fileExists(atPath: _fileUrl.path) {
  468. try?FileManager.default.removeItem(atPath: _fileUrl.path)
  469. }
  470. return url
  471. }
  472. @objc class func saveWatermarkDocumentForCompress(document: CPDFDocument, to url: URL, imageQuality: Int) -> URL? {
  473. guard let _document = self._saveDocumentForWatermark(document: document) else {
  474. return nil
  475. }
  476. // _document.write(to: _document.documentURL)
  477. // 保存文档
  478. let result = _document.writeOptimize(to: url, withOptions: [.imageQualityOption : imageQuality])
  479. // 清除临时数据
  480. if let _fileUrl = _document.documentURL, FileManager.default.fileExists(atPath: _fileUrl.path) {
  481. try?FileManager.default.removeItem(atPath: _fileUrl.path)
  482. }
  483. if (result) {
  484. return url
  485. }
  486. return nil
  487. }
  488. @objc class func saveWatermarkDocumentForFlatten(document: CPDFDocument, to url: URL) -> URL? {
  489. guard let _document = self._saveDocumentForWatermark(document: document) else {
  490. return nil
  491. }
  492. // 保存文档
  493. let result = _document.writeFlatten(to: url)
  494. // 清除临时数据
  495. if let _fileUrl = _document.documentURL, FileManager.default.fileExists(atPath: _fileUrl.path) {
  496. try?FileManager.default.removeItem(atPath: _fileUrl.path)
  497. }
  498. if (result) {
  499. return url
  500. }
  501. return nil
  502. }
  503. @objc class func saveDocumentToTemp(document: CPDFDocument, fileID: String, needUnlock: Bool = true) -> URL? {
  504. // 将文档存入临时目录
  505. if let data = self.getTempFloderPath(), !FileManager.default.fileExists(atPath: data) {
  506. if let rootPath = self.getTempRootPath(), !FileManager.default.fileExists(atPath: rootPath) {
  507. try?FileManager.default.createDirectory(atPath: rootPath, withIntermediateDirectories: false)
  508. }
  509. try?FileManager.default.createDirectory(atPath: data, withIntermediateDirectories: false)
  510. }
  511. guard let filePath = self.getTempFloderPath()?.stringByAppendingPathComponent("temp_saveDocumentFor\(fileID).pdf") else {
  512. return nil
  513. }
  514. // 清除临时数据
  515. if (FileManager.default.fileExists(atPath: filePath)) {
  516. try?FileManager.default.removeItem(atPath: filePath)
  517. }
  518. document.write(toFile: filePath)
  519. if (!FileManager.default.fileExists(atPath: filePath)) {
  520. return nil
  521. }
  522. guard let _document = CPDFDocument(url: URL(fileURLWithPath: filePath)) else {
  523. return nil
  524. }
  525. if (!needUnlock) {
  526. return _document.documentURL
  527. }
  528. // 如果加锁,则去解锁
  529. if let pwd = document.password, !pwd.isEmpty, _document.isLocked {
  530. _document.unlock(withPassword: document.password)
  531. }
  532. if (_document.isLocked) {
  533. return nil
  534. }
  535. return _document.documentURL
  536. }
  537. @objc class func trackEvent(type: KMSubscribeWaterMarkType) -> Void {
  538. if (type == .stamp) {
  539. KMAnalytics.trackEvent(eventName: "PDFReaderPro_Subscribe_Stamp", parameters: nil, appTarget: .all)
  540. } else if (type == .link) {
  541. KMAnalytics.trackEvent(eventName: "PDFReaderPro_Subscribe_Link", parameters: nil, appTarget: .all)
  542. } else if (type == .sign) {
  543. KMAnalytics.trackEvent(eventName: "PDFReaderPro_Subscribe_Sign", parameters: nil, appTarget: .all)
  544. } else if (type == .editText) {
  545. KMAnalytics.trackEvent(eventName: "PDFReaderPro_Subscribe_EditText", parameters: nil, appTarget: .all)
  546. } else if (type == .editImage) {
  547. KMAnalytics.trackEvent(eventName: "PDFReaderPro_Subscribe_EditImage", parameters: nil, appTarget: .all)
  548. } else if (type == .insert) {
  549. KMAnalytics.trackEvent(eventName: "PDFReaderPro_Subscribe_Insert", parameters: nil, appTarget: .all)
  550. } else if (type == .extract) {
  551. KMAnalytics.trackEvent(eventName: "PDFReaderPro_Subscribe_Extract", parameters: nil, appTarget: .all)
  552. } else if (type == .replace) {
  553. KMAnalytics.trackEvent(eventName: "PDFReaderPro_Subscribe_Replace", parameters: nil, appTarget: .all)
  554. } else if (type == .split) {
  555. KMAnalytics.trackEvent(eventName: "PDFReaderPro_Subscribe_Split", parameters: nil, appTarget: .all)
  556. } else if (type == .delete) {
  557. KMAnalytics.trackEvent(eventName: "PDFReaderPro_Subscribe_Delete", parameters: nil, appTarget: .all)
  558. } else if (type == .rotate) {
  559. KMAnalytics.trackEvent(eventName: "PDFReaderPro_Subscribe_Rotate", parameters: nil, appTarget: .all)
  560. } else if (type == .copy) {
  561. KMAnalytics.trackEvent(eventName: "PDFReaderPro_Subscribe_Copy", parameters: nil, appTarget: .all)
  562. } else if (type == .toWord) {
  563. KMAnalytics.trackEvent(eventName: "PDFReaderPro_Subscribe_ToWord", parameters: nil, appTarget: .all)
  564. } else if (type == .toExcel) {
  565. KMAnalytics.trackEvent(eventName: "PDFReaderPro_Subscribe_ToExcel", parameters: nil, appTarget: .all)
  566. } else if (type == .toPPT) {
  567. KMAnalytics.trackEvent(eventName: "PDFReaderPro_Subscribe_ToPPT", parameters: nil, appTarget: .all)
  568. } else if (type == .toRTF) {
  569. KMAnalytics.trackEvent(eventName: "PDFReaderPro_Subscribe_ToRTF", parameters: nil, appTarget: .all)
  570. } else if (type == .toCSV) {
  571. KMAnalytics.trackEvent(eventName: "PDFReaderPro_Subscribe_ToCSV", parameters: nil, appTarget: .all)
  572. } else if (type == .toHTML) {
  573. KMAnalytics.trackEvent(eventName: "PDFReaderPro_Subscribe_ToHTML", parameters: nil, appTarget: .all)
  574. } else if (type == .toText) {
  575. KMAnalytics.trackEvent(eventName: "PDFReaderPro_Subscribe_ToText", parameters: nil, appTarget: .all)
  576. } else if (type == .toImage) {
  577. KMAnalytics.trackEvent(eventName: "PDFReaderPro_Subscribe_ToImage", parameters: nil, appTarget: .all)
  578. } else if (type == .compress) {
  579. KMAnalytics.trackEvent(eventName: "PDFReaderPro_Subscribe_Compress", parameters: nil, appTarget: .all)
  580. } else if (type == .merge) {
  581. KMAnalytics.trackEvent(eventName: "PDFReaderPro_Subscribe_Merge", parameters: nil, appTarget: .all)
  582. } else if (type == .setPassword) {
  583. KMAnalytics.trackEvent(eventName: "PDFReaderPro_Subscribe_SetPassword", parameters: nil, appTarget: .all)
  584. } else if (type == .removePassword) {
  585. KMAnalytics.trackEvent(eventName: "PDFReaderPro_Subscribe_RemovePassword", parameters: nil, appTarget: .all)
  586. } else if (type == .crop) {
  587. KMAnalytics.trackEvent(eventName: "PDFReaderPro_Subscribe_Crop", parameters: nil, appTarget: .all)
  588. } else if (type == .aiTranslate) {
  589. KMAnalytics.trackEvent(eventName: "PDFReaderPro_Subscribe_AITranslate", parameters: nil, appTarget: .all)
  590. } else if (type == .aiRewrite) {
  591. KMAnalytics.trackEvent(eventName: "PDFReaderPro_Subscribe_AIRewrite", parameters: nil, appTarget: .all)
  592. } else if (type == .aiCorrect) {
  593. KMAnalytics.trackEvent(eventName: "PDFReaderPro_Subscribe_AICorrect", parameters: nil, appTarget: .all)
  594. }
  595. }
  596. // MARK: - Private Methods
  597. @objc fileprivate class func _documentAddWatermark(document: CPDFDocument) -> CPDFDocument? {
  598. // 添加水印
  599. let watermark = CPDFWatermark(document: document, type: .image)
  600. watermark?.image = NSImage(named: "KMImageNameWatermark")
  601. watermark?.horizontalPosition = .left
  602. watermark?.verticalPosition = .top
  603. watermark?.scale = 0.5
  604. document.addWatermark(watermark)
  605. // 添加 link注释
  606. var watermarkAnnoBounds = NSMakeRect(0, 0, 120, 32)
  607. for i in 0 ..< document.pageCount {
  608. guard let page = document.page(at: i) else {
  609. continue
  610. }
  611. // 水印注释 frame
  612. watermarkAnnoBounds.origin.y = page.bounds.size.height-watermarkAnnoBounds.size.height
  613. // 找到需要删除的水印注释(之前添加)
  614. var flagAnnos: [CPDFAnnotation] = []
  615. for anno in page.annotations {
  616. if let anno_link = anno as? CPDFLinkAnnotation, anno_link.url() == kKMPurchaseProductURLString, anno_link.bounds.equalTo(watermarkAnnoBounds) {
  617. flagAnnos.append(anno_link)
  618. }
  619. }
  620. // 删除之前的水印注释
  621. for anno in flagAnnos {
  622. page.removeAnnotation(anno)
  623. }
  624. // 新增新的水印注释
  625. let anno = CPDFLinkAnnotation(document: document)
  626. anno?.bounds = watermarkAnnoBounds
  627. anno?.setURL(kKMPurchaseProductURLString)
  628. page.addAnnotation(anno)
  629. }
  630. return document
  631. }
  632. @objc fileprivate class func _saveDocumentForWatermark(document: CPDFDocument) -> CPDFDocument? {
  633. // 将文档存入临时目录
  634. guard let _fileUrl = self.saveDocumentToTemp(document: document, fileID: "Watermark") else {
  635. return nil
  636. }
  637. guard let _document = CPDFDocument(url: _fileUrl) else {
  638. return nil
  639. }
  640. // 如果加锁,则去解锁
  641. if let pwd = document.password, !pwd.isEmpty, _document.isLocked {
  642. _document.unlock(withPassword: pwd)
  643. }
  644. // 添加水印
  645. return self._documentAddWatermark(document: _document)
  646. }
  647. }