【问题标题】:How to detect the orientation of a PDF page in Swift with PDFKit IOS如何使用 PDFKit IOS 在 Swift 中检测 PDF 页面的方向
【发布时间】:2021-11-17 22:00:58
【问题描述】:

我正在尝试获取 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 获得了示例项目。我查看了 previous similar question,但似乎这是在 Objective C 中。

感谢您在这件事上的帮助。

【问题讨论】:

    标签: ios swift xcode pdfkit ios-pdfkit


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-22
      • 2021-05-05
      • 2018-11-07
      • 2013-03-12
      • 2015-06-25
      • 1970-01-01
      相关资源
      最近更新 更多