KMWatermarkView.swift 52 KB

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