123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101 |
- //
- // KMNPDFPreView.swift
- // PDF Reader Pro
- //
- // Created by User-Tangchao on 2024/10/23.
- //
- import Cocoa
- class KMNPDFPreView: NSView {
- // MARK: - lazy
-
- private lazy var contentBox_: NSBox = {
- let box = NSBox()
- box.boxType = .custom
- box.titlePosition = .noTitle
- box.contentViewMargins = .zero
- box.borderWidth = 0
- return box
- }()
-
- lazy var pdfView: CPDFView = {
- let view = CPDFView()
- view.setDisplay(.singlePage)
- view.layoutDocumentView()
- view.autoScales = true
- view.delegate = self
- return view
- }()
-
- var contentInset: NSEdgeInsets = .init(top: 0, left: 0, bottom: 0, right: 0) {
- didSet {
- self.needsLayout = true
- }
- }
-
- var currentPageDidChanged: KMItemClickBlock<KMNPDFPreView>?
- deinit {
- KMPrint("KMNPDFPreView deinit.")
- }
-
- convenience init(fileUrl: URL, password: String?) {
- self.init()
-
- initSubviews()
- initDefaultValue()
-
- setFileUrl(fileUrl, password: password)
- }
-
- override func awakeFromNib() {
- super.awakeFromNib()
-
- initSubviews()
- initDefaultValue()
- }
-
- func initSubviews() {
- self.addSubview(self.contentBox_)
-
- self.contentBox_.contentView = self.pdfView
- }
-
- func initDefaultValue() {
- self.contentBox_.borderWidth = 0
- // self.contentBox_.borderColor = .red
- }
-
- func setFileUrl(_ fileUrl: URL, password: String?) {
- let document = CPDFDocument(url: fileUrl)
- let isLocked = document?.isLocked ?? false
- if isLocked {
- document?.unlock(withPassword: password ?? "")
- }
- pdfView.document = document
- }
-
- override func layout() {
- super.layout()
-
- let theFrame = self.bounds
- let contentX = self.contentInset.left
- let contentY = self.contentInset.top
- let contentW = NSWidth(theFrame)-contentX-self.contentInset.right
- let contentH = NSHeight(theFrame)-contentY-self.contentInset.bottom
- self.contentBox_.frame = NSMakeRect(contentX, contentY, contentW, contentH)
- }
-
- override func draw(_ dirtyRect: NSRect) {
- super.draw(dirtyRect)
- // Drawing code here.
- }
- }
- extension KMNPDFPreView: CPDFViewDelegate {
- func pdfViewCurrentPageDidChanged(_ pdfView: CPDFView!) {
- self.currentPageDidChanged?(self, 1)
- }
- }
|