KMWatermarkView.swift 55 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285
  1. //
  2. // KMWatermarkView.swift
  3. // PDF Reader Pro
  4. //
  5. // Created by lizhe on 2023/11/14.
  6. //
  7. import Cocoa
  8. enum KMWatermarkManagerType {
  9. case add
  10. case edit
  11. case use
  12. }
  13. typealias KMWatermarkViewOperateCallBack = (_ watermark: KMWatermarkModel, _ countType: Int) -> ()
  14. typealias KMWatermarkViewCancelAction = (_ view: KMWatermarkView) -> Void
  15. class KMWatermarkView: KMBaseXibView, NSTextFieldDelegate, NSComboBoxDelegate, NSTextViewDelegate, CPDFViewDelegate {
  16. //顶部box
  17. @IBOutlet var typeBox: NSBox!
  18. @IBOutlet var txtButton: NSButton!
  19. @IBOutlet var fileButton: NSButton!
  20. @IBOutlet var filePathLabel: NSTextField!
  21. @IBOutlet var browsebutton: NSButton!
  22. @IBOutlet var ratioLabel: NSTextField!
  23. @IBOutlet var ratioTextField: NSTextField!
  24. @IBOutlet var ratioStepper: NSStepper!
  25. @IBOutlet var fontLabel: NSTextField!
  26. @IBOutlet var fontComboBox: NSComboBox!
  27. @IBOutlet var fontSizeLabel: NSTextField!
  28. @IBOutlet var fontSizeCombobox: NSComboBox!
  29. @IBOutlet var colorLabel: NSTextField!
  30. @IBOutlet var colorWell: NSColorWell!
  31. @IBOutlet var watermarkStringTextView: NSTextView!
  32. var maskView: KMBookletMaskView?
  33. //底部box
  34. @IBOutlet var appearanceBox: NSBox!
  35. @IBOutlet var angleLabel: NSTextField!
  36. @IBOutlet var angleTextF: NSTextField!
  37. @IBOutlet var angleStepper: NSStepper!
  38. @IBOutlet var left45IndicateView: KMAngleIndicateView!
  39. @IBOutlet var horizontalIndicateView: KMAngleIndicateView!
  40. @IBOutlet var right45IndicateView: KMAngleIndicateView!
  41. @IBOutlet var alphaLabel: NSTextField!
  42. @IBOutlet var alphaSlider: NSSlider!
  43. @IBOutlet var alphaTextField: NSTextField!
  44. @IBOutlet var alphaStepper: NSStepper!
  45. @IBOutlet var watermarkPositionLabel: NSTextField!
  46. @IBOutlet var OnPageButton: NSButton!
  47. @IBOutlet var backPageButton: NSButton!
  48. @IBOutlet var positionView: KMPostionIndicateView!
  49. @IBOutlet var horizentalGapLabel: NSTextField!
  50. @IBOutlet var verticalGapLabel: NSTextField!
  51. @IBOutlet var horizentalGapTextField: NSTextField!
  52. @IBOutlet var verticalFapTextField: NSTextField!
  53. @IBOutlet var horizentalGapStepper: NSStepper!
  54. @IBOutlet var verticalGapStepper: NSStepper!
  55. @IBOutlet var pageRangeLabel: NSTextField!
  56. @IBOutlet var pageRangeComboBox: NSComboBox!
  57. //保存到模版按钮
  58. @IBOutlet var saveToTemplateButton: NSButton!
  59. @IBOutlet var templateNameLabel: NSTextField!
  60. @IBOutlet var templateNameTextField: NSTextField!
  61. @IBOutlet var isTileWater: NSButton!
  62. @IBOutlet var spacingHorTextField: NSTextField!
  63. @IBOutlet var spacingHorStepper: NSStepper!
  64. @IBOutlet var horizentalIconButton: NSButton!
  65. @IBOutlet var verticalIconButton: NSButton!
  66. @IBOutlet var spacingVerTextField: NSTextField!
  67. @IBOutlet var spacingStepper: NSStepper!
  68. //底部按钮
  69. @IBOutlet var batchButton: NSButton!
  70. @IBOutlet var cancelButton: NSButton!
  71. @IBOutlet var applyButton: NSButton!
  72. //左侧
  73. @IBOutlet var previewPageButton: NSButton!
  74. @IBOutlet var nextPageButton: NSButton!
  75. @IBOutlet var currentPageIndexTextF: NSTextField!
  76. @IBOutlet var totalPageCountLabel: NSTextField!
  77. @IBOutlet var pdfView: KMWatermarkPDFView!
  78. var fontModified: Bool = false
  79. var currentType: Int = 0
  80. var filePath: String = Bundle.main.path(forResource: "Quick Start Guide", ofType: "pdf") ?? ""
  81. var password: String = ""
  82. var originalWatermark: KMWatermarkModel = KMWatermarkModel()
  83. var watermark: KMWatermarkModel = KMWatermarkModel()
  84. var type: KMWatermarkManagerType = .use {
  85. didSet {
  86. if type == .edit {
  87. } else {
  88. watermark.watermarkID = KMWatermarkManager.defaultManager.fetchAvailableName()
  89. }
  90. self.templateNameTextField.stringValue = self.watermark.watermarkID
  91. }
  92. }
  93. var pdfDocument: CPDFDocument? {
  94. didSet {
  95. self._fileAttri = KMFileAttribute()
  96. self._fileAttri?.password = self.pdfDocument?.password ?? ""
  97. self._fileAttri?.filePath = self.pdfDocument?.documentURL?.path ?? ""
  98. self.password = pdfDocument?.password ?? ""
  99. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.3) {
  100. self.pdfView.watermark = self.watermark
  101. self.pdfView.document = self.pdfDocument
  102. self.pdfView.autoScales = true
  103. self.pdfView.documentView().enclosingScrollView?.scrollerStyle = .overlay
  104. self.pdfView.documentView().enclosingScrollView?.hasVerticalScroller = false
  105. self.pdfView.documentView().enclosingScrollView?.hasHorizontalScroller = false
  106. }
  107. // self.reloadData()
  108. }
  109. }
  110. var onlyManagerTemplate: Bool = true
  111. var isHiddenBatchBtn: Bool = false
  112. private var _fileAttri: KMFileAttribute?
  113. var cancelAction: KMWatermarkViewCancelAction?
  114. var operateCallBack: KMWatermarkViewOperateCallBack?
  115. convenience init(baseFile filePath: String, watermark: KMWatermarkModel, password: String, type: KMWatermarkManagerType, fileType countType: Int) {
  116. self.init()
  117. self.filePath = filePath
  118. self.password = password
  119. self.originalWatermark = watermark.copy() as! KMWatermarkModel
  120. self.watermark = watermark.copy() as! KMWatermarkModel
  121. self.type = type
  122. self.pdfDocument = CPDFDocument(url: URL(fileURLWithPath: self.filePath))
  123. self.currentType = countType
  124. if pdfDocument?.isLocked ?? false {
  125. pdfDocument?.unlock(withPassword: password)
  126. }
  127. }
  128. override func setup() {
  129. pdfView.setDisplay(.singlePage)
  130. // if (pdfView.documentView() != nil) {
  131. // pdfView.setDisplay(.singlePage)
  132. // pdfView.documentView().enclosingScrollView?.scrollerStyle = .overlay
  133. // pdfView.documentView().enclosingScrollView?.hasVerticalScroller = false
  134. // pdfView.documentView().enclosingScrollView?.hasHorizontalScroller = false
  135. // }
  136. for i in 0..<3 {
  137. for j in 0..<3 {
  138. if i == Int(watermark.horizontalMode) && j == Int(watermark.verticalMode) {
  139. positionView.style = KMPositionIndicateViewStyle(rawValue: i + 3 * j)!
  140. }
  141. }
  142. }
  143. positionView.styleChangedCallBack = { [weak self] in
  144. guard let self = self else { return }
  145. self.watermark.horizontalMode = self.positionView.style.rawValue % 3
  146. self.watermark.verticalMode = self.positionView.style.rawValue / 3
  147. self.updatePDFView()
  148. }
  149. currentPageIndexTextF.stringValue = "1"
  150. // let numberFormatter = currentPageIndexTextF.formatter as! NumberFormatter
  151. // numberFormatter.maximum = NSNumber(value: pdfDocument!.pageCount)
  152. pdfView.delegate = self
  153. let formatter = TextFieldFormatter.init()
  154. formatter.allowedCharacterSet = "-"
  155. self.angleTextF.formatter = formatter
  156. angleTextF.delegate = self
  157. let formatter2 = TextFieldFormatter.init()
  158. formatter2.allowedCharacterSet = "%"
  159. self.alphaTextField.formatter = formatter2
  160. alphaTextField.delegate = self
  161. let formatter3 = TextFieldFormatter.init()
  162. formatter3.allowedCharacterSet = ".-"
  163. self.horizentalGapTextField.formatter = formatter3
  164. horizentalGapTextField.delegate = self
  165. let formatter4 = TextFieldFormatter.init()
  166. formatter4.allowedCharacterSet = ".-"
  167. self.verticalFapTextField.formatter = formatter4
  168. verticalFapTextField.delegate = self
  169. let formatter5 = TextFieldFormatter.init()
  170. formatter5.allowedCharacterSet = ""
  171. self.spacingHorTextField.formatter = formatter5
  172. spacingHorTextField.delegate = self
  173. let formatter6 = TextFieldFormatter.init()
  174. formatter6.allowedCharacterSet = ""
  175. self.spacingVerTextField.formatter = formatter6
  176. spacingVerTextField.delegate = self
  177. left45IndicateView.style = .left45
  178. left45IndicateView.touchCallBack = { [weak self] in
  179. guard let self = self else { return }
  180. self.watermark.rotation = -45
  181. self.angleStepper.doubleValue = self.watermark.rotation
  182. self.angleTextF.stringValue = "\(self.angleStepper.intValue)"
  183. self.checkAngle()
  184. self.updatePDFView()
  185. }
  186. horizontalIndicateView.style = .horizontal
  187. horizontalIndicateView.touchCallBack = { [weak self] in
  188. guard let self = self else { return }
  189. self.watermark.rotation = 0
  190. self.angleStepper.doubleValue = 0
  191. self.angleTextF.stringValue = "\(0)"
  192. self.checkAngle()
  193. self.updatePDFView()
  194. }
  195. right45IndicateView.style = .right45
  196. right45IndicateView.touchCallBack = { [weak self] in
  197. guard let self = self else { return }
  198. self.watermark.rotation = 45
  199. self.angleStepper.doubleValue = self.watermark.rotation
  200. self.angleTextF.stringValue = "\(self.angleStepper.intValue)"
  201. self.checkAngle()
  202. self.updatePDFView()
  203. }
  204. saveToTemplateButton.isEnabled = onlyManagerTemplate
  205. // if type == .use {
  206. // saveToTemplateButton.isHidden = true
  207. // saveToTemplateButton.state = .off
  208. // } else {
  209. // saveToTemplateButton.isHidden = false
  210. // saveToTemplateButton.state = .on
  211. // }
  212. if type == .add {
  213. applyButton.title = NSLocalizedString("Apply", comment: "")
  214. batchButton.isHidden = true
  215. } else if type == .edit {
  216. applyButton.title = NSLocalizedString("Apply", comment: "")
  217. batchButton.isHidden = true
  218. } else if type == .use {
  219. applyButton.title = NSLocalizedString("Save & Apply", comment: "")
  220. }
  221. filePathLabel.stringValue = ""
  222. filePathLabel.placeholderString = NSLocalizedString("Select a File", comment: "")
  223. fontSizeCombobox.removeAllItems()
  224. fontSizeCombobox.addItems(withObjectValues: ["9","10","11","12","13","14","18","24","36","48","64","72","96","144","288"])
  225. fontSizeCombobox.formatter = TextFieldFormatter()
  226. watermarkStringTextView.delegate = self
  227. self.watermarkStringTextView.insertionPointColor = .labelColor
  228. pageRangeComboBox.removeAllItems()
  229. pageRangeComboBox.addItems(withObjectValues: [
  230. NSLocalizedString("All Pages", comment: ""),
  231. NSLocalizedString("Odd Pages Only", comment: ""),
  232. NSLocalizedString("Even Pages Only", comment: ""),
  233. NSLocalizedString("e.g. 1,3-5,10", comment: "")
  234. ])
  235. pageRangeComboBox.placeholderString = NSLocalizedString("e.g. 1,3-5,10", comment: "")
  236. pageRangeComboBox.delegate = nil
  237. pageRangeComboBox.selectItem(at: 0)
  238. pageRangeComboBox.isEditable = false
  239. pageRangeComboBox.delegate = self
  240. fontSizeCombobox.wantsLayer = true
  241. pageRangeComboBox.wantsLayer = true
  242. fontSizeCombobox.layer?.cornerRadius = 3.0
  243. pageRangeComboBox.layer?.cornerRadius = 3.0
  244. self.verticalFapTextField.delegate = self
  245. self.horizentalGapTextField.delegate = self
  246. self.spacingHorTextField.delegate = self
  247. self.spacingVerTextField.delegate = self
  248. }
  249. override func updateLanguage() {
  250. typeBox.title = NSLocalizedString("Source", comment: "")
  251. typeBox.titleFont = NSFont.systemFont(ofSize: 13)
  252. txtButton.title = NSLocalizedString("Text", comment: "")
  253. fileButton.title = NSLocalizedString("File", comment: "")
  254. browsebutton.title = NSLocalizedString("Choose...", comment: "")
  255. ratioLabel.stringValue = "\(NSLocalizedString("Ratio", comment: "")):"
  256. fontLabel.stringValue = NSLocalizedString("Font", comment: "")
  257. horizentalIconButton.toolTip = NSLocalizedString("Horizontal Distance", comment: "")
  258. verticalIconButton.toolTip = NSLocalizedString("Vertical Distance", comment: "")
  259. fontSizeLabel.stringValue = "\(NSLocalizedString("Font Size", comment: "")):"
  260. colorLabel.stringValue = "\(NSLocalizedString("Color", comment: "")):"
  261. templateNameTextField.stringValue = watermark.watermarkID ?? ""
  262. appearanceBox.title = NSLocalizedString("Appearance", comment: "")
  263. appearanceBox.titleFont = NSFont.systemFont(ofSize: 13)
  264. angleLabel.stringValue = "\(NSLocalizedString("Rotation", comment: "")):"
  265. alphaLabel.stringValue = "\(NSLocalizedString("Opacity", comment: "")):"
  266. watermarkPositionLabel.stringValue = "\(NSLocalizedString("Position", comment: "")):"
  267. OnPageButton.title = NSLocalizedString("Appear on top of page", comment: "")
  268. backPageButton.title = NSLocalizedString("Appear behind page", comment: "")
  269. pageRangeLabel.stringValue = "\(NSLocalizedString("Page Range", comment: "")):"
  270. isTileWater.title = NSLocalizedString("Tile", comment: "")
  271. OnPageButton.toolTip = NSLocalizedString("Appear on top of page", comment: "")
  272. backPageButton.toolTip = NSLocalizedString("Appear behind page", comment: "")
  273. pageRangeLabel.toolTip = "\(NSLocalizedString("Page Range", comment: "")):"
  274. horizentalGapLabel.stringValue = "X:"
  275. verticalGapLabel.stringValue = "Y:"
  276. saveToTemplateButton.title = NSLocalizedString("Add to Template", comment: "")
  277. templateNameLabel.stringValue = NSLocalizedString("Name:", comment: "")
  278. batchButton.title = NSLocalizedString("Batch", comment: "")
  279. cancelButton.title = NSLocalizedString("Cancel", comment: "")
  280. }
  281. override func reloadData() {
  282. guard let pdfDocument = pdfDocument else { return }
  283. let opacity = round(watermark.opacity * 100) / 100
  284. watermarkStringTextView.string = watermark.text
  285. colorWell.color = watermark.getTextColor()
  286. totalPageCountLabel.stringValue = "/ \(pdfDocument.pageCount)"
  287. fontSizeCombobox.stringValue = "\(Int(watermark.getTextFontSize()))"
  288. angleStepper.doubleValue = Double(watermark.rotation)
  289. angleTextF.stringValue = "\(angleStepper.intValue)"
  290. OnPageButton.state = watermark.isFront ? .on : .off
  291. backPageButton.state = watermark.isFront ? .off : .on
  292. alphaSlider.doubleValue = watermark.opacity
  293. alphaStepper.doubleValue = watermark.opacity
  294. alphaTextField.stringValue = "\(Int(opacity * 100))%"
  295. ratioStepper.doubleValue = watermark.scale
  296. ratioTextField.stringValue = "\(Int(opacity * 100))%"
  297. fontComboBox.stringValue = "\(watermark.getTextFontSize() )"
  298. filePathLabel.stringValue = watermark.imagePath
  299. batchButton.isHidden = isHiddenBatchBtn
  300. if !isHiddenBatchBtn {
  301. self.batchButton.isHidden = type != .use
  302. }
  303. if currentType == 0 {
  304. changeTypeBoxState(isTextWatermark: true)
  305. } else {
  306. changeTypeBoxState(isTextWatermark: false)
  307. }
  308. switch watermark.pageRangeType {
  309. case .all:
  310. pageRangeComboBox.isEditable = false
  311. pageRangeComboBox.selectItem(at: 0)
  312. case .odd:
  313. pageRangeComboBox.isEditable = false
  314. pageRangeComboBox.selectItem(at: 1)
  315. case .even:
  316. pageRangeComboBox.isEditable = false
  317. pageRangeComboBox.selectItem(at: 2)
  318. case .other:
  319. pageRangeComboBox.isEditable = true
  320. pageRangeComboBox.selectItem(at: 3)
  321. pageRangeComboBox.stringValue = watermark.pagesString
  322. }
  323. for i in 0..<3 {
  324. for j in 0..<3 {
  325. if i == Int(watermark.horizontalMode) && j == Int(watermark.verticalMode) {
  326. self.positionView.style = KMPositionIndicateViewStyle(rawValue: i + 3 * j)!
  327. }
  328. }
  329. }
  330. verticalGapStepper.doubleValue = Double(watermark.verticalSpace)
  331. verticalFapTextField.stringValue = "\(verticalGapStepper.doubleValue)"
  332. horizentalGapStepper.doubleValue = Double(watermark.horizontalSpace)
  333. horizentalGapTextField.stringValue = "\(horizentalGapStepper.doubleValue)"
  334. spacingHorTextField.stringValue = "\(watermark.tileHorizontalSpace)"
  335. spacingVerTextField.stringValue = "\(watermark.tileVerticalSpace)"
  336. spacingHorStepper.doubleValue = Double(watermark.tileHorizontalSpace)
  337. spacingStepper.doubleValue = Double(watermark.tileVerticalSpace)
  338. if watermark.isTilePage {
  339. isTileWater.state = .on
  340. spacingHorTextField.isEnabled = true
  341. spacingHorStepper.isEnabled = true
  342. spacingVerTextField.isEnabled = true
  343. spacingStepper.isEnabled = true
  344. } else {
  345. isTileWater.state = .off
  346. spacingHorTextField.isEnabled = false
  347. spacingHorStepper.isEnabled = false
  348. spacingVerTextField.isEnabled = false
  349. spacingStepper.isEnabled = false
  350. }
  351. pageRangeComboxAction(Any.self)
  352. checkAngle()
  353. }
  354. override func addNotification() {
  355. NotificationCenter.default.addObserver(self, selector: #selector(pageChangeNotification), name: NSNotification.Name.CPDFViewPageChanged, object: self.pdfView)
  356. }
  357. func updatePDFView() {
  358. // pdfView.needsDisplay = true
  359. km_synchronized(self) {
  360. self.pdfView.setNeedsDisplayForVisiblePages()
  361. }
  362. }
  363. func checkAngle() {
  364. left45IndicateView.isSelcted = false
  365. horizontalIndicateView.isSelcted = false
  366. right45IndicateView.isSelcted = false
  367. switch watermark.rotation {
  368. case -45:
  369. left45IndicateView.isSelcted = true
  370. case 0:
  371. horizontalIndicateView.isSelcted = true
  372. case 45:
  373. right45IndicateView.isSelcted = true
  374. default:
  375. break
  376. }
  377. }
  378. func changeTypeBoxState(isTextWatermark: Bool) {
  379. if isTextWatermark {
  380. txtButton.state = .on
  381. watermarkStringTextView.isEditable = true
  382. watermarkStringTextView.isSelectable = true
  383. fontSizeCombobox.isEnabled = true
  384. colorWell.isEnabled = true
  385. fileButton.state = .off
  386. browsebutton.isEnabled = false
  387. ratioTextField.isEnabled = false
  388. ratioStepper.isEnabled = false
  389. watermark.text = watermarkStringTextView.string
  390. watermarkStringTextView.string = watermarkStringTextView.string
  391. watermark.image = nil
  392. if watermarkStringTextView.string.isEmpty == false {
  393. applyButton.isEnabled = true
  394. batchButton.isEnabled = true
  395. } else {
  396. applyButton.isEnabled = false
  397. batchButton.isEnabled = false
  398. }
  399. } else {
  400. txtButton.state = .off
  401. watermarkStringTextView.isEditable = false
  402. watermarkStringTextView.isSelectable = false
  403. fontSizeCombobox.isEnabled = false
  404. colorWell.isEnabled = false
  405. fileButton.state = .on
  406. browsebutton.isEnabled = true
  407. ratioTextField.isEnabled = true
  408. ratioStepper.isEnabled = true
  409. watermark.text = ""
  410. if let _image = NSImage(contentsOfFile: watermark.imagePath ) {
  411. watermark.image = _image
  412. }
  413. if filePathLabel.stringValue.isEmpty == false {
  414. applyButton.isEnabled = true
  415. batchButton.isEnabled = true
  416. } else {
  417. applyButton.isEnabled = false
  418. batchButton.isEnabled = false
  419. }
  420. }
  421. updatePDFView()
  422. }
  423. func checkPageRangeValidate(_ pageRangeString: String) -> Bool {
  424. var fileAttribute = self._fileAttri
  425. if fileAttribute == nil {
  426. fileAttribute = KMFileAttribute()
  427. fileAttribute?.password = self.pdfDocument?.password ?? ""
  428. fileAttribute?.filePath = self.pdfDocument?.documentURL.path ?? ""
  429. self._fileAttri = fileAttribute
  430. }
  431. fileAttribute?.bAllPage = false
  432. fileAttribute?.pagesString = self.pageRangeComboBox.stringValue
  433. var pageRange: KMPageRange = .all
  434. let pageRangeType: KMWatermarkeModelPageRangeType = watermark.pageRangeType
  435. if pageRangeType == .all {
  436. pageRange = .all
  437. } else if pageRangeType == .even {
  438. pageRange = .even
  439. } else if pageRangeType == .odd {
  440. pageRange = .odd
  441. } else if pageRangeType == .other {
  442. pageRange = .custom
  443. }
  444. fileAttribute?.pagesType = pageRange
  445. if let cnt = fileAttribute?.fetchSelectPages().count, cnt == 0 {
  446. return false
  447. }
  448. return true
  449. }
  450. @objc func controlTextDidEndEditing(_ obj: Notification) {
  451. if obj.object as? NSComboBox == self.fontSizeCombobox {
  452. var textSize = CGFloat(Int(self.fontSizeCombobox.stringValue) ?? 0)
  453. if textSize == 0 {
  454. textSize = 48
  455. if self.watermark.isTilePage {
  456. textSize = 18
  457. }
  458. }
  459. self.watermark.textFont = KMWatermarkAdjectiveText.font(name: "Helvetica", size: textSize)
  460. self.fontSizeCombobox.stringValue = "\(Int(textSize))"
  461. self.updatePDFView()
  462. } else if obj.object as? NSTextField == self.ratioTextField {
  463. let formatter = self.ratioTextField.formatter as? NumberFormatter
  464. _ = formatter?.number(from: self.ratioTextField.stringValue)?.floatValue ?? 0
  465. self.ratioStepper.doubleValue = Double(self.watermark.scale)
  466. self.updatePDFView()
  467. } else if obj.object as? NSTextField == self.angleTextF {
  468. self.watermark.rotation = CGFloat(Int(self.angleTextF.stringValue) ?? 0)
  469. self.angleStepper.doubleValue = self.watermark.rotation
  470. self.checkAngle()
  471. self.updatePDFView()
  472. } else if obj.object as? NSTextField == self.alphaTextField {
  473. let floatValue = self.alphaTextField.stringValue.replacingOccurrences(of: "%", with: "").stringToCGFloat() * 0.01
  474. self.alphaSlider.doubleValue = Double(floatValue)
  475. self.alphaStepper.doubleValue = Double(floatValue)
  476. self.watermark.opacity = Double(floatValue)
  477. self.updatePDFView()
  478. } else if obj.object as? NSComboBox == self.pageRangeComboBox {
  479. if self.pageRangeComboBox.indexOfSelectedItem == -1 {
  480. if !self.checkPageRangeValidate(self.pageRangeComboBox.stringValue) {
  481. let alert = NSAlert()
  482. alert.alertStyle = .critical
  483. alert.messageText = "\(String(describing: self.pdfDocument?.documentURL.lastPathComponent)) \(NSLocalizedString("Invalid page range or the page number is out of range. Please try again.", comment: ""))"
  484. alert.runModal()
  485. self.window?.makeFirstResponder(self.pageRangeComboBox)
  486. return
  487. } else {
  488. self.watermark.pagesString = self.pageRangeComboBox.stringValue
  489. self.updatePDFView()
  490. }
  491. }
  492. } else if obj.object as? NSTextField == self.verticalFapTextField {
  493. self.watermark.verticalSpace = CGFloat(Int(self.verticalFapTextField.stringValue) ?? 0)
  494. self.verticalGapStepper.doubleValue = Double(self.watermark.verticalSpace)
  495. self.updatePDFView()
  496. } else if obj.object as? NSTextField == self.horizentalGapTextField {
  497. self.watermark.horizontalSpace = CGFloat(Int(self.horizentalGapTextField.stringValue) ?? 0)
  498. self.horizentalGapStepper.doubleValue = Double(self.watermark.horizontalSpace)
  499. self.updatePDFView()
  500. } else if obj.object as? NSTextField == self.currentPageIndexTextF {
  501. self.pdfView.go(toPageIndex: (Int(self.currentPageIndexTextF.stringValue) ?? 0 - 1), animated: false)
  502. } else if obj.object as? NSTextField == self.spacingHorTextField {
  503. self.watermark.tileHorizontalSpace = CGFloat(Int(self.spacingHorTextField.stringValue) ?? 0)
  504. self.spacingHorStepper.doubleValue = Double(self.watermark.tileHorizontalSpace)
  505. self.updatePDFView()
  506. } else if obj.object as? NSTextField == self.spacingVerTextField {
  507. self.watermark.tileVerticalSpace = CGFloat(Int(self.spacingVerTextField.stringValue) ?? 0)
  508. self.spacingStepper.doubleValue = Double(self.watermark.tileVerticalSpace)
  509. self.updatePDFView()
  510. }
  511. }
  512. @objc func comboBoxSelectionDidChange(_ notification: Notification) {
  513. if notification.object as? NSComboBox == self.pageRangeComboBox {
  514. self.pageRangeComboBox.isEditable = false
  515. if self.pageRangeComboBox.indexOfSelectedItem == 0 {
  516. self.watermark.pageRangeType = .all
  517. } else if self.pageRangeComboBox.indexOfSelectedItem == 1 {
  518. self.watermark.pageRangeType = .odd
  519. } else if self.pageRangeComboBox.indexOfSelectedItem == 2 {
  520. self.watermark.pageRangeType = .even
  521. } else {
  522. self.watermark.pageRangeType = .other
  523. self.pageRangeComboBox.stringValue = ""
  524. self.pageRangeComboBox.isEditable = true
  525. self.window?.makeFirstResponder(self.pageRangeComboBox)
  526. }
  527. }
  528. }
  529. @objc func textDidChange(_ notification: Notification) {
  530. if notification.object as? NSTextView == self.watermarkStringTextView {
  531. self.watermark.text = self.watermarkStringTextView.string
  532. self.applyButton.isEnabled = !self.watermark.text.isEmpty
  533. self.batchButton.isEnabled = !self.watermark.text.isEmpty
  534. self.updatePDFView()
  535. }
  536. }
  537. func isDamageImage(_ image: NSImage?, imagePath path: String) -> Bool {
  538. let addImageAnnotation = (NSSearchPathForDirectoriesInDomains(.applicationSupportDirectory, .userDomainMask, true).last! as NSString).appendingPathComponent(Bundle.main.bundleIdentifier!)
  539. if !FileManager.default.fileExists(atPath: addImageAnnotation) {
  540. try? FileManager.default.createDirectory(atPath: addImageAnnotation, withIntermediateDirectories: false, attributes: nil)
  541. }
  542. let data = image?.tiffRepresentation
  543. let imageRep = NSBitmapImageRep(data: data!)
  544. imageRep?.size = image?.size ?? NSSize.zero
  545. var imageData: Data?
  546. if path.lowercased() == "png" {
  547. imageData = imageRep?.representation(using: .png, properties: [:])
  548. } else {
  549. imageData = imageRep?.representation(using: .jpeg, properties: [:])
  550. }
  551. let rPath = (addImageAnnotation as NSString).appendingPathComponent("waterAnnotation.png")
  552. if ((try? imageData?.write(to: URL(fileURLWithPath: rPath), options: .atomic)) == nil) {
  553. return true
  554. } else {
  555. return false
  556. }
  557. }
  558. func tagString() -> String {
  559. let dateFormatter = DateFormatter()
  560. dateFormatter.dateFormat = "yyMMddHHmmss"
  561. return "\(dateFormatter.string(from: Date()))\(arc4random() % 10000)"
  562. }
  563. // MARK: - Action
  564. // NSNotification
  565. @objc func pageChangeNotification(_ notification: Notification) {
  566. currentPageIndexTextF.stringValue = "\(pdfView.currentPage().pageIndex() + 1)"
  567. }
  568. // 开始转圈,隐藏转圈提示
  569. func showWaitting() {
  570. if maskView == nil {
  571. maskView = KMBookletMaskView(frame: NSRect(x: 0, y: 0, width: window?.frame.size.width ?? 0, height: window?.frame.size.height ?? 0))
  572. }
  573. window?.contentView?.addSubview(maskView!)
  574. }
  575. func hideWaitting() {
  576. maskView?.removeFromSuperview()
  577. }
  578. override func mouseDown(with event: NSEvent) {
  579. super.mouseDown(with: event)
  580. window?.makeFirstResponder(nil)
  581. }
  582. }
  583. extension KMWatermarkView {
  584. @IBAction func buttonClicked_SwitchTextWatermark(_ sender: Any) {
  585. currentType = 0
  586. changeTypeBoxState(isTextWatermark: true)
  587. }
  588. @IBAction func buttonClicked_SwitchFileWaterMark(_ sender: Any) {
  589. currentType = 1
  590. changeTypeBoxState(isTextWatermark: false)
  591. }
  592. @IBAction func buttonClicked_BrowseFile(_ sender: Any) {
  593. let openPanel = NSOpenPanel()
  594. openPanel.canChooseDirectories = false
  595. openPanel.canChooseFiles = true
  596. openPanel.allowsMultipleSelection = false
  597. openPanel.allowedFileTypes = ["jpg", "jpeg", "png", "pdf"]
  598. openPanel.beginSheetModal(for: window!) { (result) in
  599. if result == NSApplication.ModalResponse.OK {
  600. guard let url = openPanel.url else { return }
  601. let filePath = url.path
  602. if filePath.extension.lowercased() == ".pdf" {
  603. let pdf = CPDFDocument(url: url)
  604. guard !pdf!.isEncrypted else { return }
  605. self.showWaitting()
  606. let convert = KMPDFConvert()
  607. convert.convertType = .png
  608. convert.filePath = url.path
  609. convert.pages = [1]
  610. convert.outputFolderPath = (NSSearchPathForDirectoriesInDomains(.applicationSupportDirectory, .userDomainMask, true).last! as NSString).appendingPathComponent(Bundle.main.bundleIdentifier!)
  611. convert.outputFileName = "pdfConvertPng"
  612. KMPDFConvertManager.defaultManager.convert(convert: convert, completion: { (finished, error) in
  613. self.hideWaitting()
  614. if finished {
  615. let outputFilePath = convert.outputFilePath
  616. if FileManager.default.fileExists(atPath: outputFilePath) {
  617. let fimagePath = (try? FileManager.default.subpaths(atPath: outputFilePath))?.first
  618. let pdfPath = convert.outputFilePath + "/" + fimagePath!
  619. var newPath = (convert.outputFolderPath as NSString).appendingPathComponent(self.tagString())
  620. newPath = (newPath as NSString).appendingPathComponent(((url.path as NSString).lastPathComponent as NSString).deletingPathExtension + ".png")
  621. do {
  622. try FileManager.default.copyItem(atPath: pdfPath, toPath: newPath)
  623. try FileManager.default.removeItem(atPath: convert.outputFilePath)
  624. } catch {
  625. print(error.localizedDescription)
  626. }
  627. let image = NSImage(contentsOfFile: pdfPath)
  628. if self.isDamageImage(image, imagePath: pdfPath) {
  629. let alert = NSAlert()
  630. alert.alertStyle = .critical
  631. alert.messageText = "The file \"\(url.lastPathComponent)\" could not be opened."
  632. alert.informativeText = "It may be damaged or use a file format that PDF Reader Pro doesn’t recognize."
  633. alert.addButton(withTitle: "Cancel")
  634. alert.beginSheetModal(for: NSApp.mainWindow!) { (response) in
  635. if response == NSApplication.ModalResponse.alertFirstButtonReturn {
  636. // Cancel button clicked
  637. }
  638. }
  639. return
  640. }
  641. self.filePathLabel.stringValue = url.path
  642. self.watermark.imagePath = pdfPath
  643. self.watermark.image = NSImage(contentsOfFile: pdfPath)
  644. self.watermark.text = ""
  645. self.templateNameTextField.stringValue = self.watermark.watermarkID
  646. self.applyButton.isEnabled = true
  647. self.batchButton.isEnabled = true
  648. self.pdfView.setNeedsDisplay(NSRect.zero)
  649. }
  650. }
  651. })
  652. } else {
  653. let image = NSImage(contentsOfFile: url.path)
  654. if image == nil || self.isDamageImage(image, imagePath: url.path) {
  655. let alert = NSAlert()
  656. alert.alertStyle = .critical
  657. alert.messageText = "The file \"\(url.lastPathComponent)\" could not be opened."
  658. alert.informativeText = "It may be damaged or use a file format that PDF Reader Pro doesn’t recognize."
  659. alert.addButton(withTitle: "Cancel")
  660. alert.beginSheetModal(for: NSApp.mainWindow!) { (response) in
  661. if response == NSApplication.ModalResponse.alertFirstButtonReturn {
  662. // Cancel button clicked
  663. }
  664. }
  665. return
  666. }
  667. self.filePathLabel.stringValue = url.path
  668. self.watermark.imagePath = url.path
  669. self.watermark.image = NSImage(contentsOfFile: url.path)
  670. self.watermark.text = ""
  671. self.templateNameTextField.stringValue = self.watermark.watermarkID
  672. self.applyButton.isEnabled = true
  673. self.batchButton.isEnabled = true
  674. self.pdfView.setNeedsDisplay(NSRect.zero)
  675. }
  676. }
  677. }
  678. }
  679. @IBAction func buttonClicked_Batch(_ sender: Any) {
  680. let needSave = saveToTemplateButton.state == .on
  681. if needSave {
  682. if templateNameTextField.stringValue.isEmpty {
  683. self.watermark.watermarkID = templateNameTextField.stringValue
  684. } else {
  685. self.watermark.watermarkID = KMWatermarkManager.defaultManager.fetchAvailableName()
  686. }
  687. let result = KMWatermarkManager.defaultManager.addWatermark(watermark: self.watermark)
  688. if !result {
  689. return
  690. }
  691. }
  692. if let operateCallBack = self.operateCallBack {
  693. operateCallBack(self.watermark, currentType)
  694. }
  695. // self.cancelAction?(self)
  696. }
  697. @IBAction func buttonClicked_Cancel(_ sender: Any) {
  698. self.pdfView.watermark = nil
  699. self.pdfView.background = nil
  700. self.pdfView.headerFooter = nil
  701. self.cancelAction?(self)
  702. }
  703. @IBAction func buttonClicked_Done(_ sender: Any) {
  704. guard let pdfDocument = pdfDocument else { return }
  705. if self.watermark.imagePath.count == 0 {
  706. if self.watermark.text.isEmpty {
  707. return
  708. }
  709. }
  710. if checkPageRangeValidate(pageRangeComboBox.stringValue) {
  711. watermark.pagesString = pageRangeComboBox.stringValue
  712. self.updatePDFView()
  713. window?.makeFirstResponder(self)
  714. }
  715. let needSave = saveToTemplateButton.state == .on
  716. var pages = [Int]()
  717. switch pageRangeComboBox.indexOfSelectedItem {
  718. case 0:
  719. pages = Array(0..<Int(pdfDocument.pageCount))
  720. case 1:
  721. pages = Array(stride(from: 0, to: Int(pdfDocument.pageCount), by: 2))
  722. case 2:
  723. pages = Array(stride(from: 1, to: Int(pdfDocument.pageCount), by: 2))
  724. default:
  725. var fileAttribute = self._fileAttri
  726. if fileAttribute == nil {
  727. fileAttribute = KMFileAttribute()
  728. fileAttribute?.password = pdfDocument.password ?? ""
  729. fileAttribute?.filePath = pdfDocument.documentURL?.path ?? ""
  730. self._fileAttri = fileAttribute
  731. }
  732. fileAttribute?.bAllPage = false
  733. fileAttribute?.pagesType = .custom
  734. fileAttribute?.pagesString = pageRangeComboBox.stringValue
  735. let selectPages = fileAttribute?.fetchSelectPages() ?? []
  736. if selectPages.count != 0 {
  737. pages = selectPages.map { $0 - 1 }
  738. } else {
  739. let alert = NSAlert()
  740. alert.alertStyle = .critical
  741. alert.messageText = "\(fileAttribute?.filePath.lastPathComponent ?? "") \(NSLocalizedString("Invalid page range or the page number is out of range. Please try again.", comment: ""))"
  742. alert.runModal()
  743. return
  744. }
  745. }
  746. watermark.pagesString = pages.isEmpty ? "" : pages.map { "\($0)" }.joined(separator: ",")
  747. if needSave {
  748. if self.templateNameTextField.stringValue.isEmpty {
  749. self.watermark.watermarkID = KMWatermarkManager.defaultManager.fetchAvailableName()
  750. } else {
  751. self.watermark.watermarkID = self.templateNameTextField.stringValue
  752. }
  753. if KMWatermarkManager.defaultManager.watermarks.contains(self.originalWatermark) {
  754. let _ = KMWatermarkManager.defaultManager.removeWatermark(watermark: self.originalWatermark)
  755. let _ = KMWatermarkManager.defaultManager.addWatermark(watermark: self.watermark)
  756. } else {
  757. let _ = KMWatermarkManager.defaultManager.addWatermark(watermark: self.watermark)
  758. }
  759. }
  760. if self.type == .edit || self.type == .add {
  761. if let operateCallBack = self.operateCallBack {
  762. operateCallBack(self.watermark, currentType)
  763. }
  764. self.cancelAction?(self)
  765. } else if self.type == .use {
  766. let fileName = "\(pdfDocument.documentURL?.deletingPathExtension().lastPathComponent ?? NSLocalizedString("Untitled", comment: ""))_Watermark"
  767. let savePanelAccessoryViewController = KMSavePanelAccessoryController()
  768. let savePanel = NSSavePanel()
  769. savePanel.nameFieldStringValue = fileName
  770. savePanel.allowedFileTypes = ["pdf"]
  771. savePanel.accessoryView = savePanelAccessoryViewController.view
  772. savePanel.beginSheetModal(for: self.window!) { [unowned self] result in
  773. if result == NSApplication.ModalResponse.OK {
  774. self.addWatermark(model: self.watermark, toPath: savePanel.url!.path) { success in
  775. if success {
  776. if savePanelAccessoryViewController.openAutomaticButton.state == .on {
  777. NSDocumentController.shared.openDocument(withContentsOf: savePanel.url!, display: true) { (document, documentWasAlreadyOpen, error) in
  778. }
  779. } else {
  780. NSWorkspace.shared.activateFileViewerSelecting([savePanel.url!])
  781. }
  782. self.cancelAction?(self)
  783. }
  784. }
  785. }
  786. }
  787. }
  788. }
  789. @IBAction func colorWellColorChanged(_ sender: NSColorWell) {
  790. let convertedColor = sender.color.usingColorSpaceName(NSColorSpaceName.deviceRGB)
  791. if let rgbColor = convertedColor {
  792. self.watermark.textColor = KMWatermarkAdjectiveText.color(red: rgbColor.redComponent, green: rgbColor.greenComponent, blue: rgbColor.blueComponent, alpha: rgbColor.alphaComponent)
  793. updatePDFView()
  794. }
  795. }
  796. @IBAction func radioStepperAction(_ sender: NSStepper) {
  797. self.ratioTextField.stringValue = "\(Int(sender.doubleValue * 100))%"
  798. self.watermark.scale = sender.doubleValue
  799. updatePDFView()
  800. }
  801. @IBAction func angleStepperAction(_ sender: NSStepper) {
  802. self.angleTextF.stringValue = "\(sender.doubleValue)"
  803. self.watermark.rotation = sender.doubleValue
  804. checkAngle()
  805. updatePDFView()
  806. }
  807. @IBAction func alphaSliderAction(_ sender: NSSlider) {
  808. self.watermark.opacity = sender.doubleValue
  809. self.alphaStepper.doubleValue = sender.doubleValue
  810. self.alphaTextField.stringValue = "\(Int(sender.doubleValue * 100))%"
  811. updatePDFView()
  812. }
  813. @IBAction func verticalStepperAction(_ sender: NSStepper) {
  814. self.verticalFapTextField.stringValue = "\(sender.doubleValue)"
  815. self.watermark.verticalSpace = sender.doubleValue
  816. updatePDFView()
  817. }
  818. @IBAction func tileVerticalStepperAction(_ sender: NSStepper) {
  819. self.watermark.tileVerticalSpace = sender.doubleValue
  820. self.spacingVerTextField.stringValue = "\(sender.doubleValue)"
  821. self.watermark.tileVerticalSpace = sender.doubleValue
  822. updatePDFView()
  823. }
  824. @IBAction func horizentalStepperAction(_ sender: NSStepper) {
  825. self.watermark.horizontalSpace = sender.doubleValue
  826. self.horizentalGapTextField.stringValue = "\(sender.doubleValue)"
  827. self.watermark.horizontalSpace = sender.doubleValue
  828. updatePDFView()
  829. }
  830. @IBAction func tileHorizentalStepperAction(_ sender: NSStepper) {
  831. self.watermark.tileHorizontalSpace = sender.doubleValue
  832. self.spacingHorTextField.stringValue = "\(sender.doubleValue)"
  833. self.watermark.tileHorizontalSpace = sender.doubleValue
  834. updatePDFView()
  835. }
  836. @IBAction func alphaSteperAction(_ sender: NSStepper) {
  837. self.alphaTextField.stringValue = "\(Int(sender.doubleValue * 100))%"
  838. self.watermark.opacity = sender.doubleValue
  839. self.alphaSlider.doubleValue = sender.doubleValue
  840. updatePDFView()
  841. }
  842. @IBAction func onPageButtonAction(_ sender: Any) {
  843. self.backPageButton.state = .off
  844. self.watermark.isFront = true
  845. updatePDFView()
  846. }
  847. @IBAction func backPageButtonAction(_ sender: Any) {
  848. self.OnPageButton.state = .off
  849. self.watermark.isFront = false
  850. updatePDFView()
  851. }
  852. @IBAction func onPageTileButtonAction(_ sender: Any) {
  853. self.watermark.isTilePage = !self.watermark.isTilePage
  854. if self.type != .edit && !self.fontModified && self.txtButton.state == .on {
  855. if self.watermark.isTilePage {
  856. let textSize = self.watermark.getTextFontSize() == 48 ? 18 : self.watermark.getTextFontSize()
  857. self.isTileWater.state = .on
  858. self.fontSizeCombobox.stringValue = "\(Int(textSize))"
  859. self.watermark.textFont = KMWatermarkAdjectiveText.font(name: "Helvetica", size: textSize)
  860. } else {
  861. let textSize = self.watermark.getTextFontSize() == 18 ? 48 : self.watermark.getTextFontSize()
  862. self.fontSizeCombobox.stringValue = "\(Int(textSize))"
  863. self.watermark.textFont = KMWatermarkAdjectiveText.font(name: "Helvetica", size: textSize)
  864. }
  865. }
  866. self.spacingHorTextField.isEnabled = self.watermark.isTilePage
  867. self.spacingHorStepper.isEnabled = self.watermark.isTilePage
  868. self.spacingVerTextField.isEnabled = self.watermark.isTilePage
  869. self.spacingStepper.isEnabled = self.watermark.isTilePage
  870. updatePDFView()
  871. }
  872. @IBAction func goPrevious(_ sender: Any) {
  873. if pdfView.canGoToPreviousPage() {
  874. pdfView.goToPreviousPage(sender)
  875. }
  876. let index = pdfDocument?.index(for: pdfView.currentPage())
  877. // currentPageIndexTextF.stringValue = "\(index! + 1)"
  878. }
  879. @IBAction func goNext(_ sender: Any) {
  880. if pdfView.canGoToNextPage() {
  881. pdfView.goToNextPage(sender)
  882. }
  883. let index = pdfDocument!.index(for: pdfView.currentPage())
  884. // currentPageIndexTextF.stringValue = "\(index + 1)"
  885. }
  886. @IBAction func fontSizeComboxAction(_ sender: NSComboBox) {
  887. let textSize = CGFloat(Int(fontSizeCombobox.stringValue) ?? 0)
  888. self.watermark.textFont = KMWatermarkAdjectiveText.font(name: "Helvetica", size: textSize)
  889. fontModified = true
  890. updatePDFView()
  891. }
  892. @IBAction func pageRangeComboxAction(_ sender: Any) {
  893. pageRangeComboBox.isEditable = false
  894. var pages = [Int]()
  895. switch pageRangeComboBox.indexOfSelectedItem {
  896. case 0:
  897. for i in 0..<pdfDocument!.pageCount {
  898. pages.append(Int(i))
  899. }
  900. watermark.pageRangeType = .all
  901. case 1:
  902. for i in 0..<pdfDocument!.pageCount where i % 2 == 0 {
  903. pages.append(Int(i))
  904. }
  905. watermark.pageRangeType = .odd
  906. case 2:
  907. for i in 0..<pdfDocument!.pageCount where i % 2 != 0 {
  908. pages.append(Int(i))
  909. }
  910. watermark.pageRangeType = .even
  911. default:
  912. var fileAttribute = self._fileAttri
  913. if fileAttribute == nil {
  914. fileAttribute = KMFileAttribute()
  915. fileAttribute?.filePath = pdfDocument?.documentURL?.path ?? ""
  916. self._fileAttri = fileAttribute
  917. }
  918. fileAttribute?.bAllPage = false
  919. fileAttribute?.pagesString = pageRangeComboBox.stringValue
  920. watermark.pageRangeType = .other
  921. pageRangeComboBox.isEditable = true
  922. window?.makeFirstResponder(pageRangeComboBox)
  923. let selectPages = fileAttribute?.fetchSelectPages() ?? []
  924. pages = selectPages.map { $0 - 1 }
  925. }
  926. if !pages.isEmpty {
  927. watermark.pagesString = pages.map { "\($0)" }.joined(separator: ",")
  928. } else {
  929. watermark.pagesString = ""
  930. }
  931. updatePDFView()
  932. }
  933. }
  934. extension KMWatermarkView {
  935. class func addWatermarkForOutSide(document: CPDFDocument, model: KMWatermarkModel, toPath: String, completion: @escaping (_ result: Bool) -> ()) {
  936. DispatchQueue.main.async {
  937. let wm = KMWatermarkView()
  938. wm.pdfView = KMWatermarkPDFView()
  939. wm.pdfView.document = document
  940. wm.password = document.password ?? ""
  941. wm.addWatermark(model: model, toPath: toPath, completion: completion)
  942. }
  943. }
  944. func addWatermark(model: KMWatermarkModel, toPath: String, completion: @escaping (_ result: Bool) -> ()) {
  945. DispatchQueue.global().async {
  946. let waterDocument = CPDFDocument(url: self.pdfView.document.documentURL)
  947. guard let waterDocumentT = waterDocument else { return }
  948. if self.password.isEmpty == false {
  949. waterDocumentT.unlock(withPassword: self.password)
  950. }
  951. var property: CPDFWatermark!
  952. var scale: CGFloat = model.scale
  953. if model.image != nil {
  954. property = CPDFWatermark(document: waterDocument, type: .image)
  955. property.image = model.image
  956. } else {
  957. property = CPDFWatermark(document: waterDocument, type: .text)
  958. property.text = model.text
  959. property.textColor = model.getTextColor()
  960. scale = model.getTextFontSize() / 24.0
  961. }
  962. property.scale = scale
  963. property.rotation = -model.rotation
  964. property.opacity = model.opacity
  965. property.tx = model.horizontalSpace
  966. property.ty = model.verticalSpace
  967. property.isFront = model.isFront
  968. var pageString: String = ""
  969. if (model.pageRangeType == .all) {
  970. for i in 0..<waterDocumentT.pageCount {
  971. pageString.append("\(i)")
  972. if (i != waterDocumentT.pageCount-1) {
  973. pageString.append(",")
  974. }
  975. }
  976. } else if (model.pageRangeType == .odd) {
  977. for i in 0 ..< waterDocumentT.pageCount {
  978. if (i % 2 == 0) {
  979. pageString.append("\(i)")
  980. } else {
  981. continue
  982. }
  983. if (i != waterDocumentT.pageCount-1) {
  984. pageString.append(",")
  985. }
  986. }
  987. } else if (model.pageRangeType == .even) {
  988. for i in 0 ..< waterDocumentT.pageCount {
  989. if (i % 2 == 1) {
  990. pageString.append("\(i)")
  991. } else {
  992. continue
  993. }
  994. if (i != waterDocumentT.pageCount-1) {
  995. pageString.append(",")
  996. }
  997. }
  998. } else {
  999. pageString = model.pagesString
  1000. }
  1001. property.pageString = pageString
  1002. property.isTilePage = model.isTilePage
  1003. property.horizontalSpacing = model.tileHorizontalSpace / scale
  1004. property.verticalSpacing = model.tileVerticalSpace / scale
  1005. if (model.verticalMode == 0) {
  1006. property.verticalPosition = .top
  1007. } else if (model.verticalMode == 1) {
  1008. property.verticalPosition = .center
  1009. } else if (model.verticalMode == 2) {
  1010. property.verticalPosition = .bottom
  1011. }
  1012. if (model.horizontalMode == 0) {
  1013. property.horizontalPosition = .left
  1014. } else if (model.horizontalMode == 1) {
  1015. property.horizontalPosition = .center
  1016. } else if (model.horizontalMode == 2) {
  1017. property.horizontalPosition = .right
  1018. }
  1019. model.watermark = property
  1020. waterDocumentT.addWatermark(property)
  1021. /// 保存到临时路径
  1022. let documentPath = NSTemporaryDirectory()
  1023. let tempPath: String = "\(documentPath)/\(toPath.lastPathComponent)"
  1024. if (FileManager.default.fileExists(atPath: tempPath)) {
  1025. try?FileManager.default.removeItem(atPath: tempPath)
  1026. }
  1027. let result = waterDocumentT.write(to: URL(fileURLWithPath: tempPath))
  1028. if (result) {
  1029. if (FileManager.default.fileExists(atPath: toPath)) {
  1030. try?FileManager.default.removeItem(atPath: toPath)
  1031. }
  1032. try?FileManager.default.moveItem(atPath: tempPath, toPath: toPath)
  1033. } else {
  1034. try?FileManager.default.removeItem(atPath: tempPath)
  1035. }
  1036. DispatchQueue.main.async {
  1037. completion(result)
  1038. }
  1039. }
  1040. // static func loadAllWatermarks() {
  1041. // self.watermarkArray.removeAll()
  1042. // let watermarks: Array<CPDFWatermark> = self.preView.document.watermarks()
  1043. // for watermark in watermarks {
  1044. // let model = KMWatermarkModel()
  1045. // model.scale = watermark.scale
  1046. // model.rotation = -watermark.rotation
  1047. // model.opacity = watermark.opacity
  1048. // model.verticalSpace = watermark.tx
  1049. // model.horizontalSpace = watermark.ty
  1050. // model.pagesString = watermark.pageString
  1051. //// model.textColor = watermark.textColor
  1052. // model.isFront = watermark.isFront
  1053. // model.isTilePage = watermark.isTilePage
  1054. // model.tileVerticalSpace = watermark.verticalSpacing
  1055. // model.tileHorizontalSpace = watermark.horizontalSpacing
  1056. //
  1057. // if (watermark.type == .text) {
  1058. // model.text = watermark.text
  1059. //// model.textFont
  1060. // model.scale = watermark.scale * 24
  1061. // } else if (watermark.type == .image) {
  1062. // model.image = watermark.image
  1063. // }
  1064. //
  1065. // if (watermark.verticalPosition == .top) {
  1066. // model.verticalMode = 0
  1067. // } else if (watermark.verticalPosition == .center) {
  1068. // model.verticalMode = 1
  1069. // } else if (watermark.verticalPosition == .bottom) {
  1070. // model.verticalMode = 2
  1071. // }
  1072. //
  1073. // if (watermark.horizontalPosition == .left) {
  1074. // model.horizontalMode = 0
  1075. // } else if (watermark.horizontalPosition == .center) {
  1076. // model.horizontalMode = 1
  1077. // } else if (watermark.horizontalPosition == .right) {
  1078. // model.horizontalMode = 2
  1079. // }
  1080. //
  1081. // model.watermark = watermark
  1082. // self.watermarkArray.append(model)
  1083. // }
  1084. // }
  1085. }
  1086. func deleteWatermarks(toPath: String, completion: @escaping (_ result: Bool) -> ()) -> () {
  1087. if (self.pdfView.document.watermarks().count <= 0) {
  1088. completion(false)
  1089. }
  1090. DispatchQueue.global().async {
  1091. let array: Array<CPDFWatermark> = self.pdfView.document.watermarks()
  1092. for model in array {
  1093. self.pdfView.document.removeWatermark(model)
  1094. }
  1095. /// 保存到临时路径
  1096. let documentPath = NSTemporaryDirectory()
  1097. let tempPath: String = "\(documentPath)/\(toPath.lastPathComponent)"
  1098. if (FileManager.default.fileExists(atPath: tempPath)) {
  1099. try?FileManager.default.removeItem(atPath: tempPath)
  1100. }
  1101. let result = self.pdfView.document.write(to: URL(fileURLWithPath: tempPath))
  1102. if (result) {
  1103. if (FileManager.default.fileExists(atPath: toPath)) {
  1104. try?FileManager.default.removeItem(atPath: toPath)
  1105. }
  1106. try?FileManager.default.moveItem(atPath: tempPath, toPath: toPath)
  1107. } else {
  1108. try?FileManager.default.removeItem(atPath: tempPath)
  1109. }
  1110. DispatchQueue.main.async {
  1111. completion(result)
  1112. }
  1113. }
  1114. }
  1115. }