[SOLVED] How to detect the orientation of a PDF page in Swift with PDFKit IOS


I’m trying to get the orientation property of a PDF document. The purpose is, I would like to add a button widget in a location that depends on the orientation of the PDF document.

For example:

     func openPDFDocument() {
            if let documentURL = Bundle.main.url(forResource: "PDF document", withExtension: "pdf"),
               let document = PDFDocument(url: documentURL),
               let page = document.page(at: 0) {
                // Set our document to the view, center it, and set a background color
                pdfView?.document = document
                pdfView?.autoScales = true
                pdfView?.backgroundColor = UIColor.lightGray
              //I think I should be able to add a code here like:
              if page.orientation = Horizontal {
                } else {
//do nothing or do something else

This is the function I would like to add in case the document is in Landscape mode:

  func insertResetButtonInto(_ page: PDFPage) {

        let pageBounds = page.bounds(for: .cropBox)

        let resetButtonBounds = CGRect(x: 90, y: pageBounds.size.height - 300, width: 106, height: 32)
        let resetButton = PDFAnnotation(bounds: resetButtonBounds, forType: PDFAnnotationSubtype(rawValue: PDFAnnotationSubtype.widget.rawValue), withProperties: nil)
        resetButton.widgetFieldType = PDFAnnotationWidgetSubtype(rawValue: PDFAnnotationWidgetSubtype.button.rawValue)
        resetButton.widgetControlType = .pushButtonControl
        resetButton.caption = "Reset"
        // Create PDFActionResetForm action to clear form fields.
        let resetFormAction = PDFActionResetForm()         
        resetFormAction.fieldsIncludedAreCleared = false
        resetButton.action = resetFormAction

I got the example project from Apple’s documentation website. I looked at a previous similar question, however it seems this was in Objective C.

I would appreciate the help in this matter.


There is no direct API to get the orientation from a PDFPage. But you can first get the page size from .mediaBox, then calculate the orientation like below.

    let pageSize = page.bounds(for: .mediaBox).size
    if pageSize.width > pageSize.height {
    } else {

Answered By – SamB

Answer Checked By – Gilberto Lyons (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *