KMWatermarkView.swift 52 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229
  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. self.cancelAction?(self)
  740. }
  741. }
  742. }
  743. }
  744. }
  745. }
  746. @IBAction func colorWellColorChanged(_ sender: NSColorWell) {
  747. self.watermark.textColor = KMWatermarkAdjectiveText.color(red: sender.color.redComponent, green: sender.color.greenComponent, blue: sender.color.blueComponent, alpha: sender.color.alphaComponent)
  748. updatePDFView()
  749. }
  750. @IBAction func radioStepperAction(_ sender: NSStepper) {
  751. self.ratioTextField.stringValue = "\(Int(sender.doubleValue * 100))%"
  752. self.watermark.scale = sender.doubleValue
  753. updatePDFView()
  754. }
  755. @IBAction func angleStepperAction(_ sender: NSStepper) {
  756. self.angleTextF.stringValue = "\(sender.doubleValue)"
  757. self.watermark.rotation = sender.doubleValue
  758. checkAngle()
  759. updatePDFView()
  760. }
  761. @IBAction func alphaSliderAction(_ sender: NSSlider) {
  762. self.watermark.opacity = sender.doubleValue
  763. self.alphaStepper.doubleValue = sender.doubleValue
  764. self.alphaTextField.stringValue = "\(Int(sender.doubleValue * 100))%"
  765. updatePDFView()
  766. }
  767. @IBAction func verticalStepperAction(_ sender: NSStepper) {
  768. self.verticalFapTextField.stringValue = "\(sender.doubleValue)"
  769. self.watermark.verticalSpace = sender.doubleValue
  770. updatePDFView()
  771. }
  772. @IBAction func tileVerticalStepperAction(_ sender: NSStepper) {
  773. self.watermark.tileVerticalSpace = sender.doubleValue
  774. self.spacingVerTextField.stringValue = "\(sender.doubleValue)"
  775. self.watermark.tileVerticalSpace = sender.doubleValue
  776. updatePDFView()
  777. }
  778. @IBAction func horizentalStepperAction(_ sender: NSStepper) {
  779. self.watermark.horizontalSpace = sender.doubleValue
  780. self.horizentalGapTextField.stringValue = "\(sender.doubleValue)"
  781. self.watermark.horizontalSpace = sender.doubleValue
  782. updatePDFView()
  783. }
  784. @IBAction func tileHorizentalStepperAction(_ sender: NSStepper) {
  785. self.watermark.tileHorizontalSpace = sender.doubleValue
  786. self.spacingHorTextField.stringValue = "\(sender.doubleValue)"
  787. self.watermark.tileHorizontalSpace = sender.doubleValue
  788. updatePDFView()
  789. }
  790. @IBAction func alphaSteperAction(_ sender: NSStepper) {
  791. self.alphaTextField.stringValue = "\(Int(sender.doubleValue * 100))%"
  792. self.watermark.opacity = sender.doubleValue
  793. self.alphaSlider.doubleValue = sender.doubleValue
  794. updatePDFView()
  795. }
  796. @IBAction func onPageButtonAction(_ sender: Any) {
  797. self.backPageButton.state = .off
  798. self.watermark.isFront = true
  799. updatePDFView()
  800. }
  801. @IBAction func backPageButtonAction(_ sender: Any) {
  802. self.OnPageButton.state = .off
  803. self.watermark.isFront = false
  804. updatePDFView()
  805. }
  806. @IBAction func onPageTileButtonAction(_ sender: Any) {
  807. self.watermark.isTilePage = !self.watermark.isTilePage
  808. if self.type != .edit && !self.fontModified && self.txtButton.state == .on {
  809. if self.watermark.isTilePage {
  810. let textSize = self.watermark.getTextFontSize() == 48 ? 18 : self.watermark.getTextFontSize()
  811. self.isTileWater.state = .on
  812. self.fontSizeCombobox.stringValue = "\(textSize)"
  813. self.watermark.textFont = KMWatermarkAdjectiveText.font(name: "Helvetica", size: textSize)
  814. } else {
  815. let textSize = self.watermark.getTextFontSize() == 18 ? 48 : self.watermark.getTextFontSize()
  816. self.fontSizeCombobox.stringValue = "\(textSize)"
  817. self.watermark.textFont = KMWatermarkAdjectiveText.font(name: "Helvetica", size: textSize)
  818. }
  819. }
  820. self.spacingHorTextField.isEnabled = self.watermark.isTilePage
  821. self.spacingHorStepper.isEnabled = self.watermark.isTilePage
  822. self.spacingVerTextField.isEnabled = self.watermark.isTilePage
  823. self.spacingStepper.isEnabled = self.watermark.isTilePage
  824. updatePDFView()
  825. }
  826. @IBAction func goPrevious(_ sender: Any) {
  827. if pdfView.canGoToPreviousPage() {
  828. pdfView.goToPreviousPage(sender)
  829. }
  830. let index = pdfDocument?.index(for: pdfView.currentPage())
  831. // currentPageIndexTextF.stringValue = "\(index! + 1)"
  832. }
  833. @IBAction func goNext(_ sender: Any) {
  834. if pdfView.canGoToNextPage() {
  835. pdfView.goToNextPage(sender)
  836. }
  837. let index = pdfDocument!.index(for: pdfView.currentPage())
  838. // currentPageIndexTextF.stringValue = "\(index + 1)"
  839. }
  840. @IBAction func fontSizeComboxAction(_ sender: NSComboBox) {
  841. let textSize = CGFloat(Int(fontSizeCombobox.stringValue) ?? 0)
  842. self.watermark.textFont = KMWatermarkAdjectiveText.font(name: "Helvetica", size: textSize)
  843. fontModified = true
  844. updatePDFView()
  845. }
  846. @IBAction func pageRangeComboxAction(_ sender: Any) {
  847. pageRangeComboBox.isEditable = false
  848. var pages = [Int]()
  849. switch pageRangeComboBox.indexOfSelectedItem {
  850. case 0:
  851. for i in 0..<pdfDocument!.pageCount {
  852. pages.append(Int(i))
  853. }
  854. watermark.pageRangeType = .all
  855. case 1:
  856. for i in 0..<pdfDocument!.pageCount where i % 2 == 0 {
  857. pages.append(Int(i))
  858. }
  859. watermark.pageRangeType = .odd
  860. case 2:
  861. for i in 0..<pdfDocument!.pageCount where i % 2 != 0 {
  862. pages.append(Int(i))
  863. }
  864. watermark.pageRangeType = .even
  865. default:
  866. var fileAttribute = self._fileAttri
  867. if fileAttribute == nil {
  868. fileAttribute = KMFileAttribute()
  869. fileAttribute?.filePath = pdfDocument?.documentURL?.path ?? ""
  870. self._fileAttri = fileAttribute
  871. }
  872. fileAttribute?.bAllPage = false
  873. fileAttribute?.pagesString = pageRangeComboBox.stringValue
  874. watermark.pageRangeType = .other
  875. pageRangeComboBox.isEditable = true
  876. window?.makeFirstResponder(pageRangeComboBox)
  877. let selectPages = fileAttribute?.fetchSelectPages() ?? []
  878. pages = selectPages.map { $0 - 1 }
  879. }
  880. if !pages.isEmpty {
  881. watermark.pagesString = pages.map { "\($0)" }.joined(separator: ",")
  882. } else {
  883. watermark.pagesString = ""
  884. }
  885. updatePDFView()
  886. }
  887. }
  888. extension KMWatermarkView {
  889. class func addWatermarkForOutSide(document: CPDFDocument, model: KMWatermarkModel, toPath: String, completion: @escaping (_ result: Bool) -> ()) {
  890. DispatchQueue.main.async {
  891. let wm = KMWatermarkView()
  892. wm.pdfView = KMWatermarkPDFView()
  893. wm.pdfView.document = document
  894. wm.password = document.password ?? ""
  895. wm.addWatermark(model: model, toPath: toPath, completion: completion)
  896. }
  897. }
  898. func addWatermark(model: KMWatermarkModel, toPath: String, completion: @escaping (_ result: Bool) -> ()) {
  899. DispatchQueue.global().async {
  900. let waterDocument = CPDFDocument(url: self.pdfView.document.documentURL)
  901. guard let waterDocumentT = waterDocument else { return }
  902. if self.password.isEmpty == false {
  903. waterDocumentT.unlock(withPassword: self.password)
  904. }
  905. var property: CPDFWatermark!
  906. var scale: CGFloat = model.scale
  907. if (!model.text.isEmpty) {
  908. property = CPDFWatermark(document: waterDocument, type: .text)
  909. property.text = model.text
  910. property.textColor = model.getTextColor()
  911. scale = model.getTextFontSize() / 24.0
  912. } else {
  913. property = CPDFWatermark(document: waterDocument, type: .image)
  914. property.image = model.image
  915. }
  916. property.scale = scale
  917. property.rotation = -model.rotation
  918. property.opacity = model.opacity
  919. property.tx = model.horizontalSpace
  920. property.ty = model.verticalSpace
  921. property.isFront = model.isFront
  922. var pageString: String = ""
  923. if (model.pageRangeType == .all) {
  924. for i in 0..<waterDocumentT.pageCount {
  925. pageString.append("\(i)")
  926. if (i != waterDocumentT.pageCount-1) {
  927. pageString.append(",")
  928. }
  929. }
  930. } else if (model.pageRangeType == .odd) {
  931. for i in 0 ..< waterDocumentT.pageCount {
  932. if (i % 2 == 0) {
  933. pageString.append("\(i)")
  934. } else {
  935. continue
  936. }
  937. if (i != waterDocumentT.pageCount-1) {
  938. pageString.append(",")
  939. }
  940. }
  941. } else if (model.pageRangeType == .even) {
  942. for i in 0 ..< waterDocumentT.pageCount {
  943. if (i % 2 == 1) {
  944. pageString.append("\(i)")
  945. } else {
  946. continue
  947. }
  948. if (i != waterDocumentT.pageCount-1) {
  949. pageString.append(",")
  950. }
  951. }
  952. } else {
  953. pageString = model.pagesString
  954. }
  955. property.pageString = pageString
  956. property.isTilePage = model.isTilePage
  957. property.horizontalSpacing = model.tileHorizontalSpace / scale
  958. property.verticalSpacing = model.tileVerticalSpace / scale
  959. if (model.verticalMode == 0) {
  960. property.verticalPosition = .top
  961. } else if (model.verticalMode == 1) {
  962. property.verticalPosition = .center
  963. } else if (model.verticalMode == 2) {
  964. property.verticalPosition = .bottom
  965. }
  966. if (model.horizontalMode == 0) {
  967. property.horizontalPosition = .left
  968. } else if (model.horizontalMode == 1) {
  969. property.horizontalPosition = .center
  970. } else if (model.horizontalMode == 2) {
  971. property.horizontalPosition = .right
  972. }
  973. model.watermark = property
  974. waterDocumentT.addWatermark(property)
  975. /// 保存到临时路径
  976. let documentPath = NSTemporaryDirectory()
  977. let tempPath: String = "\(documentPath)/\(toPath.lastPathComponent)"
  978. if (FileManager.default.fileExists(atPath: tempPath)) {
  979. try?FileManager.default.removeItem(atPath: tempPath)
  980. }
  981. let result = waterDocumentT.write(to: URL(fileURLWithPath: tempPath))
  982. if (result) {
  983. if (FileManager.default.fileExists(atPath: toPath)) {
  984. try?FileManager.default.removeItem(atPath: toPath)
  985. }
  986. try?FileManager.default.moveItem(atPath: tempPath, toPath: toPath)
  987. } else {
  988. try?FileManager.default.removeItem(atPath: tempPath)
  989. }
  990. DispatchQueue.main.async {
  991. completion(result)
  992. }
  993. }
  994. // static func loadAllWatermarks() {
  995. // self.watermarkArray.removeAll()
  996. // let watermarks: Array<CPDFWatermark> = self.preView.document.watermarks()
  997. // for watermark in watermarks {
  998. // let model = KMWatermarkModel()
  999. // model.scale = watermark.scale
  1000. // model.rotation = -watermark.rotation
  1001. // model.opacity = watermark.opacity
  1002. // model.verticalSpace = watermark.tx
  1003. // model.horizontalSpace = watermark.ty
  1004. // model.pagesString = watermark.pageString
  1005. //// model.textColor = watermark.textColor
  1006. // model.isFront = watermark.isFront
  1007. // model.isTilePage = watermark.isTilePage
  1008. // model.tileVerticalSpace = watermark.verticalSpacing
  1009. // model.tileHorizontalSpace = watermark.horizontalSpacing
  1010. //
  1011. // if (watermark.type == .text) {
  1012. // model.text = watermark.text
  1013. //// model.textFont
  1014. // model.scale = watermark.scale * 24
  1015. // } else if (watermark.type == .image) {
  1016. // model.image = watermark.image
  1017. // }
  1018. //
  1019. // if (watermark.verticalPosition == .top) {
  1020. // model.verticalMode = 0
  1021. // } else if (watermark.verticalPosition == .center) {
  1022. // model.verticalMode = 1
  1023. // } else if (watermark.verticalPosition == .bottom) {
  1024. // model.verticalMode = 2
  1025. // }
  1026. //
  1027. // if (watermark.horizontalPosition == .left) {
  1028. // model.horizontalMode = 0
  1029. // } else if (watermark.horizontalPosition == .center) {
  1030. // model.horizontalMode = 1
  1031. // } else if (watermark.horizontalPosition == .right) {
  1032. // model.horizontalMode = 2
  1033. // }
  1034. //
  1035. // model.watermark = watermark
  1036. // self.watermarkArray.append(model)
  1037. // }
  1038. // }
  1039. }
  1040. func deleteWatermarks(toPath: String, completion: @escaping (_ result: Bool) -> ()) -> () {
  1041. if (self.pdfView.document.watermarks().count <= 0) {
  1042. completion(false)
  1043. }
  1044. DispatchQueue.global().async {
  1045. let array: Array<CPDFWatermark> = self.pdfView.document.watermarks()
  1046. for model in array {
  1047. self.pdfView.document.removeWatermark(model)
  1048. }
  1049. /// 保存到临时路径
  1050. let documentPath = NSTemporaryDirectory()
  1051. let tempPath: String = "\(documentPath)/\(toPath.lastPathComponent)"
  1052. if (FileManager.default.fileExists(atPath: tempPath)) {
  1053. try?FileManager.default.removeItem(atPath: tempPath)
  1054. }
  1055. let result = self.pdfView.document.write(to: URL(fileURLWithPath: tempPath))
  1056. if (result) {
  1057. if (FileManager.default.fileExists(atPath: toPath)) {
  1058. try?FileManager.default.removeItem(atPath: toPath)
  1059. }
  1060. try?FileManager.default.moveItem(atPath: tempPath, toPath: toPath)
  1061. } else {
  1062. try?FileManager.default.removeItem(atPath: tempPath)
  1063. }
  1064. DispatchQueue.main.async {
  1065. completion(result)
  1066. }
  1067. }
  1068. }
  1069. }