0

I'm getting errors however I try to get the mediabox of a PDF Page in Swift.:

if let pdf = CGPDFDocument(pdfURL) {
    let numberOfPages = pdf.numberOfPages
    for index in 0...numberOfPages {
        let pdfPage = pdf.page(at: index)
        print(CGPDFPageGetBoxRect(pdfPage!, kCGPDFMediaBox))

}

I've also tried:

print(pdfPage.getBoxRect(kCGPDFMediaBox))

as well as using PDFDisplayBox.mediaBox, mediaBox and pretty much every other variant. It works fine in python. I can also get the info fine using PDFPage (as opposed to CGPDFPage), but I need to use CGPDFPage for other things that PDFPage can't do.)

The second part is: from what I can tell, the mediaBox result does not factor in the rotation. So a landscape page might have a portrait mediabox with a rotation of 90. Is there any easy way to get the "actual" display dimensions, or do I have to do the transformation myself?

benwiggy
  • 1,440
  • 17
  • 35

1 Answers1

3

PDF pages are numbered starting at 1, not at zero. And getBoxRect() takes a enum CGPDFBox argument in Swift 3. So this should work:

for pageNo in 1...pdf.numberOfPages {
    if let pdfPage = pdf.page(at: pageNo) {
        let mediaBox = pdfPage.getBoxRect(.mediaBox)
        print(mediaBox)
    }
}

The PDF bounding boxes do not take the page rotation into account. The following might work to compute the rotated box (untested):

// Get rotation angle and convert from degrees to radians:
let angle = CGFloat(pdfPage.rotationAngle) * CGFloat.pi / 180
// Apply rotation transform to media box:
let rotatedBox = mediaBox.applying(CGAffineTransform(rotationAngle: angle))
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
  • rotatedBox is a CGRect, but I need CGPDFBox object to pass in myCGPDFpage.getBoxRect method. Error message says: cannot convert value of type 'CGRect' to specified type 'CGPDFBox'. Please help. I am using Swift 3. Thanks. – appFormation Aug 17 '17 at 02:34
  • @appFormation: I am not sure if I understand your question. `CGPDFBox` is an enumeration and specifies *which* box you want to retrieve in `getBoxRext()` (mediabox, clip box, artbox, ...). The above code passes `.media`, you can replace that with your value. – Martin R Aug 17 '17 at 05:46