如何使用 PDFKit IOS 在 Swift 中检测 PDF 页面的方向

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

我正在尝试获取 PDF 文档的方向 属性。目的是,我想在取决于 PDF 文档方向的位置添加一个按钮小部件。

例如:

     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 {
                self.insertResetButtonInto(page)
                } else {
//do nothing or do something else
                }     
        }
    }

如果文档处于横向模式,这是我想添加的功能:

  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"
        page.addAnnotation(resetButton)
        // Create PDFActionResetForm action to clear form fields.
        let resetFormAction = PDFActionResetForm()         
        resetFormAction.fieldsIncludedAreCleared = false
        resetButton.action = resetFormAction
  
    }

我从 Apple's documentation website. I looked at a previous similar question 获得了示例项目,但它似乎在 Objective C.

在此问题上,我将不胜感激。

没有直接 API 从 PDFPage 得到 orientation。但是您可以先从 .mediaBox 获取页面大小,然后像下面这样计算方向。

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

我使用另一种方式来获取我的 pdf 页面的方向。

func IsLandscape(page: PDFPage) -> Bool {
    let pointZero = pdfView.convert(CGPoint(x: 0, y: 0), from: page)
    let pointTen = pdfView.convert(CGPoint(x: 10, y: 10), from: page)
    let caculate = pointTen.x - pointZero.x
    print("pointZero: \(pointZero), pointTen:\(pointTen)")
    if (caculate > 0) {
        print("landscape")
        return true
    }
    else {
        print("portrait")
        return false
    }
}