2

I'm having issues getting the size of a page in a PDFDocument. The following code gets the size (width and height), but the results are inconsistent. It can even be inconsistent from page to page within the same PDFDocument being tested. One specific example is that I have a pdf document composed of 11"x17" pages (rectangular, landscape orientation). Sometimes the following code gives me the correct dimensions but has the width and height backwards, and other times it will give the same dimensions for the width and the height resulting in a square shape. Is there a better way to get the width and height of a page from a PDFDocument. Ultimately, I am creating a UIImage of a page from a PDFDocument. Any suggestions there would be helpful too. Please help.

let page = pdfDocument?.page(at: pageIndex)
let pageRect = page?.bounds(for: .artBox)
let dpi: CGFloat = 300.00 / 72.0
let renderer = UIGraphicsImageRenderer(size: CGSize(width: (pageRect?.size.width)! * dpi, height: (pageRect?.size.height)! * dpi))
print("dpi =", dpi)
print("renderer width and height =", (pageRect?.size.width)! * dpi, "renderer height =", (pageRect?.size.height)! * dpi)
user2621075
  • 357
  • 4
  • 15

1 Answers1

6

The mediaBox gives the size of the page, whereas, the artBox gives the size of the drawings on the page. The following code will give you the size/dimensions of the PDFDocument page.

let page = pdfDocument?.page(at: pageIndex)
let pageRect = page?.bounds(for: .mediaBox)

print("pdf page width =", (pageRect?.size.width)!, "pdf page height =", (pageRect?.size.height)!)
MatPag
  • 41,742
  • 14
  • 105
  • 114
user2621075
  • 357
  • 4
  • 15