KMWatermarkView.swift 52 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226
  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. self.pdfView.setNeedsDisplayForVisiblePages()
  317. }
  318. func checkAngle() {
  319. left45IndicateView.isSelcted = false
  320. horizontalIndicateView.isSelcted = false
  321. right45IndicateView.isSelcted = false
  322. switch watermark.rotation {
  323. case -45:
  324. left45IndicateView.isSelcted = true
  325. case 0:
  326. horizontalIndicateView.isSelcted = true
  327. case 45:
  328. right45IndicateView.isSelcted = true
  329. default:
  330. break
  331. }
  332. }
  333. func changeTypeBoxState(isTextWatermark: Bool) {
  334. if isTextWatermark {
  335. txtButton.state = .on
  336. watermarkStringTextView.isEditable = true
  337. watermarkStringTextView.isSelectable = true
  338. fontSizeCombobox.isEnabled = true
  339. colorWell.isEnabled = true
  340. fileButton.state = .off
  341. browsebutton.isEnabled = false
  342. ratioTextField.isEnabled = false
  343. ratioStepper.isEnabled = false
  344. watermark.text = watermarkStringTextView.string
  345. watermarkStringTextView.string = watermarkStringTextView.string
  346. watermark.image = nil
  347. if watermarkStringTextView.string.isEmpty == false {
  348. applyButton.isEnabled = true
  349. batchButton.isEnabled = true
  350. } else {
  351. applyButton.isEnabled = false
  352. batchButton.isEnabled = false
  353. }
  354. } else {
  355. txtButton.state = .off
  356. watermarkStringTextView.isEditable = false
  357. watermarkStringTextView.isSelectable = false
  358. fontSizeCombobox.isEnabled = false
  359. colorWell.isEnabled = false
  360. fileButton.state = .on
  361. browsebutton.isEnabled = true
  362. ratioTextField.isEnabled = true
  363. ratioStepper.isEnabled = true
  364. watermark.text = ""
  365. if let _image = NSImage(contentsOfFile: watermark.imagePath ) {
  366. watermark.image = _image
  367. }
  368. if filePathLabel.stringValue.isEmpty == false {
  369. applyButton.isEnabled = true
  370. batchButton.isEnabled = true
  371. } else {
  372. applyButton.isEnabled = false
  373. batchButton.isEnabled = false
  374. }
  375. }
  376. updatePDFView()
  377. }
  378. func checkPageRangeValidate(_ pageRangeString: String) -> Bool {
  379. var fileAttribute = self._fileAttri
  380. if fileAttribute == nil {
  381. fileAttribute = KMFileAttribute()
  382. fileAttribute?.password = self.pdfDocument?.password ?? ""
  383. fileAttribute?.filePath = self.pdfDocument?.documentURL.path ?? ""
  384. self._fileAttri = fileAttribute
  385. }
  386. fileAttribute?.bAllPage = false
  387. fileAttribute?.pagesString = self.pageRangeComboBox.stringValue
  388. var pageRange: KMPageRange = .all
  389. let pageRangeType: KMWatermarkeModelPageRangeType = watermark.pageRangeType
  390. if pageRangeType == .all {
  391. pageRange = .all
  392. } else if pageRangeType == .even {
  393. pageRange = .even
  394. } else if pageRangeType == .odd {
  395. pageRange = .odd
  396. } else if pageRangeType == .other {
  397. pageRange = .custom
  398. }
  399. fileAttribute?.pagesType = pageRange
  400. if let cnt = fileAttribute?.fetchSelectPages().count, cnt == 0 {
  401. return false
  402. }
  403. return true
  404. }
  405. @objc func controlTextDidEndEditing(_ obj: Notification) {
  406. if obj.object as? NSComboBox == self.fontSizeCombobox {
  407. var textSize = CGFloat(Int(self.fontSizeCombobox.stringValue) ?? 0)
  408. if textSize == 0 {
  409. textSize = 48
  410. if self.watermark.isTilePage {
  411. textSize = 18
  412. }
  413. }
  414. self.watermark.textFont = KMWatermarkAdjectiveText.font(name: "Helvetica", size: textSize)
  415. self.fontSizeCombobox.stringValue = "\(textSize)"
  416. self.updatePDFView()
  417. } else if obj.object as? NSTextField == self.ratioTextField {
  418. let formatter = self.ratioTextField.formatter as? NumberFormatter
  419. _ = formatter?.number(from: self.ratioTextField.stringValue)?.floatValue ?? 0
  420. self.ratioStepper.doubleValue = Double(self.watermark.scale)
  421. self.updatePDFView()
  422. } else if obj.object as? NSTextField == self.angleTextF {
  423. self.watermark.rotation = CGFloat(Int(self.angleTextF.stringValue) ?? 0)
  424. self.angleStepper.doubleValue = self.watermark.rotation
  425. self.checkAngle()
  426. self.updatePDFView()
  427. } else if obj.object as? NSTextField == self.alphaTextField {
  428. let formatter = self.alphaTextField.formatter as? NumberFormatter
  429. _ = formatter?.number(from: self.alphaTextField.stringValue)?.floatValue ?? 0
  430. self.alphaSlider.doubleValue = Double(self.watermark.opacity)
  431. self.alphaStepper.doubleValue = Double(self.watermark.opacity)
  432. self.updatePDFView()
  433. } else if obj.object as? NSComboBox == self.pageRangeComboBox {
  434. if self.pageRangeComboBox.indexOfSelectedItem == -1 {
  435. if !self.checkPageRangeValidate(self.pageRangeComboBox.stringValue) {
  436. let alert = NSAlert()
  437. alert.alertStyle = .critical
  438. alert.messageText = "\(String(describing: self.pdfDocument?.documentURL.lastPathComponent)) \(NSLocalizedString("Invalid page range or the page number is out of range. Please try again.", comment: ""))"
  439. alert.runModal()
  440. self.window?.makeFirstResponder(self.pageRangeComboBox)
  441. return
  442. } else {
  443. self.watermark.pagesString = self.pageRangeComboBox.stringValue
  444. self.updatePDFView()
  445. }
  446. }
  447. } else if obj.object as? NSTextField == self.verticalFapTextField {
  448. self.watermark.verticalSpace = CGFloat(Int(self.verticalFapTextField.stringValue) ?? 0)
  449. self.verticalGapStepper.doubleValue = Double(self.watermark.verticalSpace)
  450. self.updatePDFView()
  451. } else if obj.object as? NSTextField == self.horizentalGapTextField {
  452. self.watermark.horizontalSpace = CGFloat(Int(self.horizentalGapTextField.stringValue) ?? 0)
  453. self.horizentalGapStepper.doubleValue = Double(self.watermark.horizontalSpace)
  454. self.updatePDFView()
  455. } else if obj.object as? NSTextField == self.currentPageIndexTextF {
  456. self.pdfView.go(toPageIndex: (Int(self.currentPageIndexTextF.stringValue) ?? 0 - 1), animated: false)
  457. } else if obj.object as? NSTextField == self.spacingHorTextField {
  458. self.watermark.tileHorizontalSpace = CGFloat(Int(self.spacingHorTextField.stringValue) ?? 0)
  459. self.spacingHorStepper.doubleValue = Double(self.watermark.tileHorizontalSpace)
  460. self.updatePDFView()
  461. } else if obj.object as? NSTextField == self.spacingVerTextField {
  462. self.watermark.tileVerticalSpace = CGFloat(Int(self.spacingVerTextField.stringValue) ?? 0)
  463. self.spacingStepper.doubleValue = Double(self.watermark.tileVerticalSpace)
  464. self.updatePDFView()
  465. }
  466. }
  467. @objc func comboBoxSelectionDidChange(_ notification: Notification) {
  468. if notification.object as? NSComboBox == self.pageRangeComboBox {
  469. self.pageRangeComboBox.isEditable = false
  470. if self.pageRangeComboBox.indexOfSelectedItem == 0 {
  471. self.watermark.pageRangeType = .all
  472. } else if self.pageRangeComboBox.indexOfSelectedItem == 1 {
  473. self.watermark.pageRangeType = .odd
  474. } else if self.pageRangeComboBox.indexOfSelectedItem == 2 {
  475. self.watermark.pageRangeType = .even
  476. } else {
  477. self.watermark.pageRangeType = .other
  478. self.pageRangeComboBox.stringValue = ""
  479. self.pageRangeComboBox.isEditable = true
  480. self.window?.makeFirstResponder(self.pageRangeComboBox)
  481. }
  482. }
  483. }
  484. @objc func textDidChange(_ notification: Notification) {
  485. if notification.object as? NSTextView == self.watermarkStringTextView {
  486. self.watermark.text = self.watermarkStringTextView.string
  487. self.applyButton.isEnabled = !self.watermark.text.isEmpty
  488. self.batchButton.isEnabled = !self.watermark.text.isEmpty
  489. self.updatePDFView()
  490. }
  491. }
  492. func isDamageImage(_ image: NSImage?, imagePath path: String) -> Bool {
  493. let addImageAnnotation = (NSSearchPathForDirectoriesInDomains(.applicationSupportDirectory, .userDomainMask, true).last! as NSString).appendingPathComponent(Bundle.main.bundleIdentifier!)
  494. if !FileManager.default.fileExists(atPath: addImageAnnotation) {
  495. try? FileManager.default.createDirectory(atPath: addImageAnnotation, withIntermediateDirectories: false, attributes: nil)
  496. }
  497. let data = image?.tiffRepresentation
  498. let imageRep = NSBitmapImageRep(data: data!)
  499. imageRep?.size = image?.size ?? NSSize.zero
  500. var imageData: Data?
  501. if path.lowercased() == "png" {
  502. imageData = imageRep?.representation(using: .png, properties: [:])
  503. } else {
  504. imageData = imageRep?.representation(using: .jpeg, properties: [:])
  505. }
  506. let rPath = (addImageAnnotation as NSString).appendingPathComponent("waterAnnotation.png")
  507. if ((try? imageData?.write(to: URL(fileURLWithPath: rPath), options: .atomic)) == nil) {
  508. return true
  509. } else {
  510. return false
  511. }
  512. }
  513. func tagString() -> String {
  514. let dateFormatter = DateFormatter()
  515. dateFormatter.dateFormat = "yyMMddHHmmss"
  516. return "\(dateFormatter.string(from: Date()))\(arc4random() % 10000)"
  517. }
  518. // MARK: - Action
  519. // NSNotification
  520. @objc func pageChangeNotification(_ notification: Notification) {
  521. currentPageIndexTextF.stringValue = "\(pdfView.currentPage().pageIndex() + 1)"
  522. }
  523. // 开始转圈,隐藏转圈提示
  524. func showWaitting() {
  525. if maskView == nil {
  526. maskView = KMBookletMaskView(frame: NSRect(x: 0, y: 0, width: window?.frame.size.width ?? 0, height: window?.frame.size.height ?? 0))
  527. }
  528. window?.contentView?.addSubview(maskView!)
  529. }
  530. func hideWaitting() {
  531. maskView?.removeFromSuperview()
  532. }
  533. override func mouseDown(with event: NSEvent) {
  534. super.mouseDown(with: event)
  535. window?.makeFirstResponder(nil)
  536. }
  537. }
  538. extension KMWatermarkView {
  539. @IBAction func buttonClicked_SwitchTextWatermark(_ sender: Any) {
  540. currentType = 0
  541. changeTypeBoxState(isTextWatermark: true)
  542. }
  543. @IBAction func buttonClicked_SwitchFileWaterMark(_ sender: Any) {
  544. currentType = 1
  545. changeTypeBoxState(isTextWatermark: false)
  546. }
  547. @IBAction func buttonClicked_BrowseFile(_ sender: Any) {
  548. let openPanel = NSOpenPanel()
  549. openPanel.canChooseDirectories = false
  550. openPanel.canChooseFiles = true
  551. openPanel.allowsMultipleSelection = false
  552. openPanel.allowedFileTypes = ["jpg", "jpeg", "png", "pdf"]
  553. openPanel.beginSheetModal(for: window!) { (result) in
  554. if result == NSApplication.ModalResponse.OK {
  555. guard let url = openPanel.url else { return }
  556. let filePath = url.path
  557. if filePath.extension.lowercased() == "pdf" {
  558. let pdf = CPDFDocument(url: url)
  559. guard !pdf!.isEncrypted else { return }
  560. self.showWaitting()
  561. let convert = KMPDFConvert()
  562. convert.convertType = .png
  563. convert.filePath = url.path
  564. convert.pages = [1]
  565. convert.outputFolderPath = (NSSearchPathForDirectoriesInDomains(.applicationSupportDirectory, .userDomainMask, true).last! as NSString).appendingPathComponent(Bundle.main.bundleIdentifier!)
  566. convert.outputFileName = "pdfConvertPng"
  567. KMPDFConvertManager.defaultManager.convert(convert: convert, completion: { (finished, error) in
  568. self.hideWaitting()
  569. if finished {
  570. let outputFilePath = convert.outputFilePath
  571. if FileManager.default.fileExists(atPath: outputFilePath) {
  572. let fimagePath = (try? FileManager.default.subpaths(atPath: outputFilePath))?.first
  573. let pdfPath = convert.outputFilePath + "/" + fimagePath!
  574. var newPath = (convert.outputFolderPath as NSString).appendingPathComponent(self.tagString())
  575. newPath = (newPath as NSString).appendingPathComponent(((url.path as NSString).lastPathComponent as NSString).deletingPathExtension + ".png")
  576. do {
  577. try FileManager.default.copyItem(atPath: pdfPath, toPath: newPath)
  578. try FileManager.default.removeItem(atPath: convert.outputFilePath)
  579. } catch {
  580. print(error.localizedDescription)
  581. }
  582. let image = NSImage(contentsOfFile: pdfPath)
  583. if self.isDamageImage(image, imagePath: pdfPath) {
  584. let alert = NSAlert()
  585. alert.alertStyle = .critical
  586. alert.messageText = "The file \"\(url.lastPathComponent)\" could not be opened."
  587. alert.informativeText = "It may be damaged or use a file format that PDF Reader Pro doesn’t recognize."
  588. alert.addButton(withTitle: "Cancel")
  589. alert.beginSheetModal(for: NSApp.mainWindow!) { (response) in
  590. if response == NSApplication.ModalResponse.alertFirstButtonReturn {
  591. // Cancel button clicked
  592. }
  593. }
  594. return
  595. }
  596. self.filePathLabel.stringValue = url.path
  597. self.watermark.imagePath = pdfPath
  598. self.watermark.image = NSImage(contentsOfFile: pdfPath)
  599. self.watermark.text = ""
  600. self.templateNameTextField.stringValue = self.watermark.watermarkID
  601. self.applyButton.isEnabled = true
  602. self.batchButton.isEnabled = true
  603. self.pdfView.setNeedsDisplay(NSRect.zero)
  604. }
  605. }
  606. })
  607. } else {
  608. let image = NSImage(contentsOfFile: url.path)
  609. if self.isDamageImage(image, imagePath: url.path) {
  610. let alert = NSAlert()
  611. alert.alertStyle = .critical
  612. alert.messageText = "The file \"\(url.lastPathComponent)\" could not be opened."
  613. alert.informativeText = "It may be damaged or use a file format that PDF Reader Pro doesn’t recognize."
  614. alert.addButton(withTitle: "Cancel")
  615. alert.beginSheetModal(for: NSApp.mainWindow!) { (response) in
  616. if response == NSApplication.ModalResponse.alertFirstButtonReturn {
  617. // Cancel button clicked
  618. }
  619. }
  620. return
  621. }
  622. self.filePathLabel.stringValue = url.path
  623. self.watermark.imagePath = url.path
  624. self.watermark.image = NSImage(contentsOfFile: url.path)
  625. self.watermark.text = ""
  626. self.templateNameTextField.stringValue = self.watermark.watermarkID
  627. self.applyButton.isEnabled = true
  628. self.batchButton.isEnabled = true
  629. self.pdfView.setNeedsDisplay(NSRect.zero)
  630. }
  631. }
  632. }
  633. }
  634. @IBAction func buttonClicked_Batch(_ sender: Any) {
  635. let needSave = saveToTemplateButton.state == .on
  636. if needSave {
  637. if templateNameTextField.stringValue.isEmpty {
  638. self.watermark.watermarkID = templateNameTextField.stringValue
  639. } else {
  640. self.watermark.watermarkID = KMWatermarkManager.defaultManager.fetchAvailableName()
  641. }
  642. let result = KMWatermarkManager.defaultManager.addWatermark(watermark: self.watermark)
  643. if !result {
  644. return
  645. }
  646. }
  647. if let operateCallBack = self.operateCallBack {
  648. operateCallBack(self.watermark, currentType)
  649. }
  650. self.cancelAction?(self)
  651. }
  652. @IBAction func buttonClicked_Cancel(_ sender: Any) {
  653. self.pdfView.watermark = nil
  654. self.pdfView.background = nil
  655. self.pdfView.headerFooter = nil
  656. self.cancelAction?(self)
  657. }
  658. @IBAction func buttonClicked_Done(_ sender: Any) {
  659. guard let pdfDocument = pdfDocument else { return }
  660. if self.watermark.imagePath.count == 0 {
  661. if self.watermark.text.isEmpty {
  662. return
  663. }
  664. }
  665. if checkPageRangeValidate(pageRangeComboBox.stringValue) {
  666. watermark.pagesString = pageRangeComboBox.stringValue
  667. self.updatePDFView()
  668. window?.makeFirstResponder(self)
  669. }
  670. let needSave = saveToTemplateButton.state == .on
  671. var pages = [Int]()
  672. switch pageRangeComboBox.indexOfSelectedItem {
  673. case 0:
  674. pages = Array(0..<Int(pdfDocument.pageCount))
  675. case 1:
  676. pages = Array(stride(from: 0, to: Int(pdfDocument.pageCount), by: 2))
  677. case 2:
  678. pages = Array(stride(from: 1, to: Int(pdfDocument.pageCount), by: 2))
  679. default:
  680. var fileAttribute = self._fileAttri
  681. if fileAttribute == nil {
  682. fileAttribute = KMFileAttribute()
  683. fileAttribute?.password = pdfDocument.password ?? ""
  684. fileAttribute?.filePath = pdfDocument.documentURL?.path ?? ""
  685. self._fileAttri = fileAttribute
  686. }
  687. fileAttribute?.bAllPage = false
  688. fileAttribute?.pagesType = .custom
  689. fileAttribute?.pagesString = pageRangeComboBox.stringValue
  690. let selectPages = fileAttribute?.fetchSelectPages() ?? []
  691. if selectPages.count != 0 {
  692. pages = selectPages.map { $0 - 1 }
  693. } else {
  694. let alert = NSAlert()
  695. alert.alertStyle = .critical
  696. alert.messageText = "\(fileAttribute?.filePath.lastPathComponent ?? "") \(NSLocalizedString("Invalid page range or the page number is out of range. Please try again.", comment: ""))"
  697. alert.runModal()
  698. return
  699. }
  700. }
  701. watermark.pagesString = pages.isEmpty ? "" : pages.map { "\($0)" }.joined(separator: ",")
  702. if self.type == .edit || self.type == .add {
  703. if needSave {
  704. if self.templateNameTextField.stringValue.isEmpty {
  705. self.watermark.watermarkID = KMWatermarkManager.defaultManager.fetchAvailableName()
  706. } else {
  707. self.watermark.watermarkID = self.templateNameTextField.stringValue
  708. }
  709. if KMWatermarkManager.defaultManager.watermarks.contains(self.originalWatermark) {
  710. let _ = KMWatermarkManager.defaultManager.removeWatermark(watermark: self.originalWatermark)
  711. let _ = KMWatermarkManager.defaultManager.addWatermark(watermark: self.watermark)
  712. } else {
  713. let _ = KMWatermarkManager.defaultManager.addWatermark(watermark: self.watermark)
  714. }
  715. }
  716. if let operateCallBack = self.operateCallBack {
  717. operateCallBack(self.watermark, currentType)
  718. }
  719. self.cancelAction?(self)
  720. } else if self.type == .use {
  721. let fileName = "\(self.pdfDocument?.documentURL.lastPathComponent ?? "Untitled")_Watermark"
  722. let savePanelAccessoryViewController = KMSavePanelAccessoryController()
  723. let savePanel = NSSavePanel()
  724. savePanel.nameFieldStringValue = fileName
  725. savePanel.allowedFileTypes = ["pdf"]
  726. savePanel.accessoryView = savePanelAccessoryViewController.view
  727. savePanel.beginSheetModal(for: self.window!) { [unowned self] result in
  728. if result == NSApplication.ModalResponse.OK {
  729. self.addWatermark(model: self.watermark, toPath: savePanel.url!.path) { success in
  730. if success {
  731. if savePanelAccessoryViewController.openAutomaticButton.state == .on {
  732. NSDocumentController.shared.openDocument(withContentsOf: savePanel.url!, display: true) { (document, documentWasAlreadyOpen, error) in
  733. }
  734. } else {
  735. NSWorkspace.shared.activateFileViewerSelecting([savePanel.url!])
  736. }
  737. }
  738. }
  739. }
  740. }
  741. }
  742. }
  743. @IBAction func colorWellColorChanged(_ sender: NSColorWell) {
  744. self.watermark.textColor = KMWatermarkAdjectiveText.color(red: sender.color.redComponent, green: sender.color.greenComponent, blue: sender.color.blueComponent, alpha: sender.color.alphaComponent)
  745. updatePDFView()
  746. }
  747. @IBAction func radioStepperAction(_ sender: NSStepper) {
  748. self.ratioTextField.stringValue = "\(Int(sender.doubleValue * 100))%"
  749. self.watermark.scale = sender.doubleValue
  750. updatePDFView()
  751. }
  752. @IBAction func angleStepperAction(_ sender: NSStepper) {
  753. self.angleTextF.stringValue = "\(sender.doubleValue)"
  754. self.watermark.rotation = sender.doubleValue
  755. checkAngle()
  756. updatePDFView()
  757. }
  758. @IBAction func alphaSliderAction(_ sender: NSSlider) {
  759. self.watermark.opacity = sender.doubleValue
  760. self.alphaStepper.doubleValue = sender.doubleValue
  761. self.alphaTextField.stringValue = "\(Int(sender.doubleValue * 100))%"
  762. updatePDFView()
  763. }
  764. @IBAction func verticalStepperAction(_ sender: NSStepper) {
  765. self.verticalFapTextField.stringValue = "\(sender.doubleValue)"
  766. self.watermark.verticalSpace = sender.doubleValue
  767. updatePDFView()
  768. }
  769. @IBAction func tileVerticalStepperAction(_ sender: NSStepper) {
  770. self.watermark.tileVerticalSpace = sender.doubleValue
  771. self.spacingVerTextField.stringValue = "\(sender.doubleValue)"
  772. self.watermark.tileVerticalSpace = sender.doubleValue
  773. updatePDFView()
  774. }
  775. @IBAction func horizentalStepperAction(_ sender: NSStepper) {
  776. self.watermark.horizontalSpace = sender.doubleValue
  777. self.horizentalGapTextField.stringValue = "\(sender.doubleValue)"
  778. self.watermark.horizontalSpace = sender.doubleValue
  779. updatePDFView()
  780. }
  781. @IBAction func tileHorizentalStepperAction(_ sender: NSStepper) {
  782. self.watermark.tileHorizontalSpace = sender.doubleValue
  783. self.spacingHorTextField.stringValue = "\(sender.doubleValue)"
  784. self.watermark.tileHorizontalSpace = sender.doubleValue
  785. updatePDFView()
  786. }
  787. @IBAction func alphaSteperAction(_ sender: NSStepper) {
  788. self.alphaTextField.stringValue = "\(Int(sender.doubleValue * 100))%"
  789. self.watermark.opacity = sender.doubleValue
  790. self.alphaSlider.doubleValue = sender.doubleValue
  791. updatePDFView()
  792. }
  793. @IBAction func onPageButtonAction(_ sender: Any) {
  794. self.backPageButton.state = .off
  795. self.watermark.isFront = true
  796. updatePDFView()
  797. }
  798. @IBAction func backPageButtonAction(_ sender: Any) {
  799. self.OnPageButton.state = .off
  800. self.watermark.isFront = false
  801. updatePDFView()
  802. }
  803. @IBAction func onPageTileButtonAction(_ sender: Any) {
  804. self.watermark.isTilePage = !self.watermark.isTilePage
  805. if self.type != .edit && !self.fontModified && self.txtButton.state == .on {
  806. if self.watermark.isTilePage {
  807. let textSize = self.watermark.getTextFontSize() == 48 ? 18 : self.watermark.getTextFontSize()
  808. self.isTileWater.state = .on
  809. self.fontSizeCombobox.stringValue = "\(textSize)"
  810. self.watermark.textFont = KMWatermarkAdjectiveText.font(name: "Helvetica", size: textSize)
  811. } else {
  812. let textSize = self.watermark.getTextFontSize() == 18 ? 48 : self.watermark.getTextFontSize()
  813. self.fontSizeCombobox.stringValue = "\(textSize)"
  814. self.watermark.textFont = KMWatermarkAdjectiveText.font(name: "Helvetica", size: textSize)
  815. }
  816. }
  817. self.spacingHorTextField.isEnabled = self.watermark.isTilePage
  818. self.spacingHorStepper.isEnabled = self.watermark.isTilePage
  819. self.spacingVerTextField.isEnabled = self.watermark.isTilePage
  820. self.spacingStepper.isEnabled = self.watermark.isTilePage
  821. updatePDFView()
  822. }
  823. @IBAction func goPrevious(_ sender: Any) {
  824. if pdfView.canGoToPreviousPage() {
  825. pdfView.goToPreviousPage(sender)
  826. }
  827. let index = pdfDocument?.index(for: pdfView.currentPage())
  828. // currentPageIndexTextF.stringValue = "\(index! + 1)"
  829. }
  830. @IBAction func goNext(_ sender: Any) {
  831. if pdfView.canGoToNextPage() {
  832. pdfView.goToNextPage(sender)
  833. }
  834. let index = pdfDocument!.index(for: pdfView.currentPage())
  835. // currentPageIndexTextF.stringValue = "\(index + 1)"
  836. }
  837. @IBAction func fontSizeComboxAction(_ sender: NSComboBox) {
  838. let textSize = CGFloat(Int(fontSizeCombobox.stringValue) ?? 0)
  839. self.watermark.textFont = KMWatermarkAdjectiveText.font(name: "Helvetica", size: textSize)
  840. fontModified = true
  841. updatePDFView()
  842. }
  843. @IBAction func pageRangeComboxAction(_ sender: Any) {
  844. pageRangeComboBox.isEditable = false
  845. var pages = [Int]()
  846. switch pageRangeComboBox.indexOfSelectedItem {
  847. case 0:
  848. for i in 0..<pdfDocument!.pageCount {
  849. pages.append(Int(i))
  850. }
  851. watermark.pageRangeType = .all
  852. case 1:
  853. for i in 0..<pdfDocument!.pageCount where i % 2 == 0 {
  854. pages.append(Int(i))
  855. }
  856. watermark.pageRangeType = .odd
  857. case 2:
  858. for i in 0..<pdfDocument!.pageCount where i % 2 != 0 {
  859. pages.append(Int(i))
  860. }
  861. watermark.pageRangeType = .even
  862. default:
  863. var fileAttribute = self._fileAttri
  864. if fileAttribute == nil {
  865. fileAttribute = KMFileAttribute()
  866. fileAttribute?.filePath = pdfDocument?.documentURL?.path ?? ""
  867. self._fileAttri = fileAttribute
  868. }
  869. fileAttribute?.bAllPage = false
  870. fileAttribute?.pagesString = pageRangeComboBox.stringValue
  871. watermark.pageRangeType = .other
  872. pageRangeComboBox.isEditable = true
  873. window?.makeFirstResponder(pageRangeComboBox)
  874. let selectPages = fileAttribute?.fetchSelectPages() ?? []
  875. pages = selectPages.map { $0 - 1 }
  876. }
  877. if !pages.isEmpty {
  878. watermark.pagesString = pages.map { "\($0)" }.joined(separator: ",")
  879. } else {
  880. watermark.pagesString = ""
  881. }
  882. updatePDFView()
  883. }
  884. }
  885. extension KMWatermarkView {
  886. class func addWatermarkForOutSide(document: CPDFDocument, model: KMWatermarkModel, toPath: String, completion: @escaping (_ result: Bool) -> ()) {
  887. DispatchQueue.main.async {
  888. let wm = KMWatermarkView()
  889. wm.pdfView = KMWatermarkPDFView()
  890. wm.pdfView.document = document
  891. wm.password = document.password ?? ""
  892. wm.addWatermark(model: model, toPath: toPath, completion: completion)
  893. }
  894. }
  895. func addWatermark(model: KMWatermarkModel, toPath: String, completion: @escaping (_ result: Bool) -> ()) {
  896. DispatchQueue.global().async {
  897. let waterDocument = CPDFDocument(url: self.pdfView.document.documentURL)
  898. guard let waterDocumentT = waterDocument else { return }
  899. if self.password.isEmpty == false {
  900. waterDocumentT.unlock(withPassword: self.password)
  901. }
  902. var property: CPDFWatermark!
  903. var scale: CGFloat = model.scale
  904. if (!model.text.isEmpty) {
  905. property = CPDFWatermark(document: waterDocument, type: .text)
  906. property.text = model.text
  907. property.textColor = model.getTextColor()
  908. scale = model.getTextFontSize() / 24.0
  909. } else {
  910. property = CPDFWatermark(document: waterDocument, type: .image)
  911. property.image = model.image
  912. }
  913. property.scale = scale
  914. property.rotation = -model.rotation
  915. property.opacity = model.opacity
  916. property.tx = model.horizontalSpace
  917. property.ty = model.verticalSpace
  918. property.isFront = model.isFront
  919. var pageString: String = ""
  920. if (model.pageRangeType == .all) {
  921. for i in 0..<waterDocumentT.pageCount {
  922. pageString.append("\(i)")
  923. if (i != waterDocumentT.pageCount-1) {
  924. pageString.append(",")
  925. }
  926. }
  927. } else if (model.pageRangeType == .odd) {
  928. for i in 0 ..< waterDocumentT.pageCount {
  929. if (i % 2 == 0) {
  930. pageString.append("\(i)")
  931. } else {
  932. continue
  933. }
  934. if (i != waterDocumentT.pageCount-1) {
  935. pageString.append(",")
  936. }
  937. }
  938. } else if (model.pageRangeType == .even) {
  939. for i in 0 ..< waterDocumentT.pageCount {
  940. if (i % 2 == 1) {
  941. pageString.append("\(i)")
  942. } else {
  943. continue
  944. }
  945. if (i != waterDocumentT.pageCount-1) {
  946. pageString.append(",")
  947. }
  948. }
  949. } else {
  950. pageString = model.pagesString
  951. }
  952. property.pageString = pageString
  953. property.isTilePage = model.isTilePage
  954. property.horizontalSpacing = model.tileHorizontalSpace / scale
  955. property.verticalSpacing = model.tileVerticalSpace / scale
  956. if (model.verticalMode == 0) {
  957. property.verticalPosition = .top
  958. } else if (model.verticalMode == 1) {
  959. property.verticalPosition = .center
  960. } else if (model.verticalMode == 2) {
  961. property.verticalPosition = .bottom
  962. }
  963. if (model.horizontalMode == 0) {
  964. property.horizontalPosition = .left
  965. } else if (model.horizontalMode == 1) {
  966. property.horizontalPosition = .center
  967. } else if (model.horizontalMode == 2) {
  968. property.horizontalPosition = .right
  969. }
  970. model.watermark = property
  971. waterDocumentT.addWatermark(property)
  972. /// 保存到临时路径
  973. let documentPath = NSTemporaryDirectory()
  974. let tempPath: String = "\(documentPath)/\(toPath.lastPathComponent)"
  975. if (FileManager.default.fileExists(atPath: tempPath)) {
  976. try?FileManager.default.removeItem(atPath: tempPath)
  977. }
  978. let result = waterDocumentT.write(to: URL(fileURLWithPath: tempPath))
  979. if (result) {
  980. if (FileManager.default.fileExists(atPath: toPath)) {
  981. try?FileManager.default.removeItem(atPath: toPath)
  982. }
  983. try?FileManager.default.moveItem(atPath: tempPath, toPath: toPath)
  984. } else {
  985. try?FileManager.default.removeItem(atPath: tempPath)
  986. }
  987. DispatchQueue.main.async {
  988. completion(result)
  989. }
  990. }
  991. // static func loadAllWatermarks() {
  992. // self.watermarkArray.removeAll()
  993. // let watermarks: Array<CPDFWatermark> = self.preView.document.watermarks()
  994. // for watermark in watermarks {
  995. // let model = KMWatermarkModel()
  996. // model.scale = watermark.scale
  997. // model.rotation = -watermark.rotation
  998. // model.opacity = watermark.opacity
  999. // model.verticalSpace = watermark.tx
  1000. // model.horizontalSpace = watermark.ty
  1001. // model.pagesString = watermark.pageString
  1002. //// model.textColor = watermark.textColor
  1003. // model.isFront = watermark.isFront
  1004. // model.isTilePage = watermark.isTilePage
  1005. // model.tileVerticalSpace = watermark.verticalSpacing
  1006. // model.tileHorizontalSpace = watermark.horizontalSpacing
  1007. //
  1008. // if (watermark.type == .text) {
  1009. // model.text = watermark.text
  1010. //// model.textFont
  1011. // model.scale = watermark.scale * 24
  1012. // } else if (watermark.type == .image) {
  1013. // model.image = watermark.image
  1014. // }
  1015. //
  1016. // if (watermark.verticalPosition == .top) {
  1017. // model.verticalMode = 0
  1018. // } else if (watermark.verticalPosition == .center) {
  1019. // model.verticalMode = 1
  1020. // } else if (watermark.verticalPosition == .bottom) {
  1021. // model.verticalMode = 2
  1022. // }
  1023. //
  1024. // if (watermark.horizontalPosition == .left) {
  1025. // model.horizontalMode = 0
  1026. // } else if (watermark.horizontalPosition == .center) {
  1027. // model.horizontalMode = 1
  1028. // } else if (watermark.horizontalPosition == .right) {
  1029. // model.horizontalMode = 2
  1030. // }
  1031. //
  1032. // model.watermark = watermark
  1033. // self.watermarkArray.append(model)
  1034. // }
  1035. // }
  1036. }
  1037. func deleteWatermarks(toPath: String, completion: @escaping (_ result: Bool) -> ()) -> () {
  1038. if (self.pdfView.document.watermarks().count <= 0) {
  1039. completion(false)
  1040. }
  1041. DispatchQueue.global().async {
  1042. let array: Array<CPDFWatermark> = self.pdfView.document.watermarks()
  1043. for model in array {
  1044. self.pdfView.document.removeWatermark(model)
  1045. }
  1046. /// 保存到临时路径
  1047. let documentPath = NSTemporaryDirectory()
  1048. let tempPath: String = "\(documentPath)/\(toPath.lastPathComponent)"
  1049. if (FileManager.default.fileExists(atPath: tempPath)) {
  1050. try?FileManager.default.removeItem(atPath: tempPath)
  1051. }
  1052. let result = self.pdfView.document.write(to: URL(fileURLWithPath: tempPath))
  1053. if (result) {
  1054. if (FileManager.default.fileExists(atPath: toPath)) {
  1055. try?FileManager.default.removeItem(atPath: toPath)
  1056. }
  1057. try?FileManager.default.moveItem(atPath: tempPath, toPath: toPath)
  1058. } else {
  1059. try?FileManager.default.removeItem(atPath: tempPath)
  1060. }
  1061. DispatchQueue.main.async {
  1062. completion(result)
  1063. }
  1064. }
  1065. }
  1066. }