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?
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))