KMNPDFPreView.swift 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  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.layoutDocumentView()
  22. view.autoScales = true
  23. view.delegate = self
  24. return view
  25. }()
  26. var contentInset: NSEdgeInsets = .init(top: 0, left: 0, bottom: 0, right: 0) {
  27. didSet {
  28. self.needsLayout = true
  29. }
  30. }
  31. var currentPageDidChanged: KMItemClickBlock<KMNPDFPreView>?
  32. deinit {
  33. KMPrint("KMNPDFPreView deinit.")
  34. }
  35. convenience init(fileUrl: URL, password: String?) {
  36. self.init()
  37. initSubviews()
  38. initDefaultValue()
  39. setFileUrl(fileUrl, password: password)
  40. }
  41. override func awakeFromNib() {
  42. super.awakeFromNib()
  43. initSubviews()
  44. initDefaultValue()
  45. }
  46. func initSubviews() {
  47. self.addSubview(self.contentBox_)
  48. self.contentBox_.contentView = self.pdfView
  49. }
  50. func initDefaultValue() {
  51. self.contentBox_.borderWidth = 0
  52. // self.contentBox_.borderColor = .red
  53. }
  54. func setFileUrl(_ fileUrl: URL, password: String?) {
  55. let document = CPDFDocument(url: fileUrl)
  56. let isLocked = document?.isLocked ?? false
  57. if isLocked {
  58. document?.unlock(withPassword: password ?? "")
  59. }
  60. pdfView.document = document
  61. }
  62. override func layout() {
  63. super.layout()
  64. let theFrame = self.bounds
  65. let contentX = self.contentInset.left
  66. let contentY = self.contentInset.top
  67. let contentW = NSWidth(theFrame)-contentX-self.contentInset.right
  68. let contentH = NSHeight(theFrame)-contentY-self.contentInset.bottom
  69. self.contentBox_.frame = NSMakeRect(contentX, contentY, contentW, contentH)
  70. }
  71. override func draw(_ dirtyRect: NSRect) {
  72. super.draw(dirtyRect)
  73. // Drawing code here.
  74. }
  75. }
  76. extension KMNPDFPreView: CPDFViewDelegate {
  77. func pdfViewCurrentPageDidChanged(_ pdfView: CPDFView!) {
  78. self.currentPageDidChanged?(self, 1)
  79. }
  80. }