KMTools.swift 27 KB

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