KMNPDFPreView.swift 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. //
  2. // KMNPDFPreView.swift
  3. // PDF Reader Pro
  4. //
  5. // Created by User-Tangchao on 2024/10/23.
  6. //
  7. import Cocoa
  8. class KMNPDFPreView: NSView {
  9. // MARK: - lazy
  10. private lazy var contentBox_: NSBox = {
  11. let box = NSBox()
  12. box.boxType = .custom
  13. box.titlePosition = .noTitle
  14. box.contentViewMargins = .zero
  15. box.borderWidth = 0
  16. return box
  17. }()
  18. lazy var pdfView: CPDFView = {
  19. let view = CPDFView()
  20. view.setDisplay(.singlePage)
  21. view.autoScales = true
  22. view.delegate = self
  23. return view
  24. }()
  25. var contentInset: NSEdgeInsets = .init(top: 0, left: 0, bottom: 0, right: 0) {
  26. didSet {
  27. self.needsLayout = true
  28. }
  29. }
  30. var currentPageDidChanged: KMItemClickBlock<KMNPDFPreView>?
  31. deinit {
  32. KMPrint("KMNPDFPreView deinit.")
  33. }
  34. convenience init(fileUrl: URL, password: String?) {
  35. self.init()
  36. initSubviews()
  37. initDefaultValue()
  38. setFileUrl(fileUrl, password: password)
  39. }
  40. override func awakeFromNib() {
  41. super.awakeFromNib()
  42. initSubviews()
  43. initDefaultValue()
  44. }
  45. func initSubviews() {
  46. self.addSubview(self.contentBox_)
  47. self.contentBox_.contentView = self.pdfView
  48. }
  49. func initDefaultValue() {
  50. self.contentBox_.borderWidth = 0
  51. // self.contentBox_.borderColor = .red
  52. }
  53. func setFileUrl(_ fileUrl: URL, password: String?) {
  54. let document = CPDFDocument(url: fileUrl)
  55. let isLocked = document?.isLocked ?? false
  56. if isLocked {
  57. document?.unlock(withPassword: password ?? "")
  58. }
  59. pdfView.document = document
  60. }
  61. override func layout() {
  62. super.layout()
  63. let theFrame = self.bounds
  64. let contentX = self.contentInset.left
  65. let contentY = self.contentInset.top
  66. let contentW = NSWidth(theFrame)-contentX-self.contentInset.right
  67. let contentH = NSHeight(theFrame)-contentY-self.contentInset.bottom
  68. self.contentBox_.frame = NSMakeRect(contentX, contentY, contentW, contentH)
  69. }
  70. override func draw(_ dirtyRect: NSRect) {
  71. super.draw(dirtyRect)
  72. // Drawing code here.
  73. }
  74. }
  75. extension KMNPDFPreView: CPDFViewDelegate {
  76. func pdfViewCurrentPageDidChanged(_ pdfView: CPDFView!) {
  77. self.currentPageDidChanged?(self, 1)
  78. }
  79. }