KMWatermarkView.swift 54 KB

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