0

I want to display a PDF in my macOS app using PDFKit. Therefore I've added a simple PDFView in IB. I want each slide of the PDF to be displayed separately and non intractable, just like an image. The only thing that should be possible is to walk through the slides with the arrow keys. I set it up with the following code:

@IBOutlet weak var pdfView: PDFView!
override func viewDidLoad() {
    super.viewDidLoad()

    if let path = Bundle.main.path(forResource: "slidedemo", ofType: "pdf") {
        let url = URL(fileURLWithPath: path)
        if let pdfDocument = PDFDocument(url: url) {
            pdfView.displayMode = .singlePage
            pdfView.document = pdfDocument
            pdfView.pageShadowsEnabled = false

            guard let pageBox = pdfView.currentPage?.bounds(for: .mediaBox) else { return }
            pdfView.frame = pageBox
        }
    }
}

I get the following from my app

enter image description here

The problem is that there is still the gray border and I am also able to scroll. I've tried the following to fix both problems, but none of them worked.

let scrollView = pdfView.subviews[0] as! NSScrollView
let clipView = pdfView.subviews[0].subviews[1] as! NSClipView

// To remove scrolling
scrollView.hasHorizontalScroller = false
scrollView.hasVerticalScroller = false
scrollView.hasHorizontalRuler = false
scrollView.hasVerticalRuler = false
scrollView.horizontalScroller = nil
scrollView.verticalScroller = nil

// To remove the border
scrollView.borderType = .noBorder
clipView.contentInsets = NSEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
clipView.automaticallyAdjustsContentInsets = false
Codey
  • 1,131
  • 2
  • 15
  • 34
  • If you want to display just like an image, why don't you use `NSImageView` instead of PDFKit? – Willeke Mar 22 '20 at 13:37
  • How do I do this? And how would I walk through the slides? – Codey Mar 22 '20 at 13:46
  • Ok I found out how to display a specified pdf page in an `NSImageView` using `NSImage(data: myPdfDocument.page(at: 0)!.dataRepresentation!)`, but I couldn't figure out how to crop pdf pages this way, which I need for my application. – Codey Mar 22 '20 at 14:42
  • 2
    Tip: use `NSImage(contentsOf: url)`, `image.cacheMode` set to `.never` and the `currentPage` property of `NSPDFImageRep`. – Willeke Mar 22 '20 at 15:54
  • @Willeke Thanks for your tip. I used `page.setBounds(croppingRect, for: .cropBox)` for the cropping. That did the trick – Codey May 14 '20 at 15:03

0 Answers0