Home > Blockchain >  PDFPage size/bounds won't change with setBounds unless setting a smaller size
PDFPage size/bounds won't change with setBounds unless setting a smaller size

Time:10-28

Code below perfectly changes bounds if setting a smaller size. But when setting a larger size it won't work. Isn't it possible to upscale a PDFPage size?

what works:

let page = PDFPage()

let rectBefore = page.bounds(for: .cropBox)
print("rectBefore \(rectBefore)")

page.setBounds(CGRect(x: 0, y: 0, width: 500, height: 500), for: .cropBox)

let rectAfter = page.bounds(for: .cropBox)
print("rectAfter \(rectAfter)")

// prints: 
// rectBefore (0.0, 0.0, 612.0, 792.0)
// rectAfter  (0.0, 0.0, 500.0, 500.0) -> Works as expected

what won't work:

let page = PDFPage()

let rectBefore = page.bounds(for: .cropBox)
print("rectBefore \(rectBefore)")

page.setBounds(CGRect(x: 0, y: 0, width: 1000, height: 1000), for: .cropBox)

let rectAfter = page.bounds(for: .cropBox)
print("rectAfter \(rectAfter)")

// prints: 
// rectBefore (0.0, 0.0, 612.0, 792.0)
// rectAfter  (0.0, 0.0, 612.0, 792.0) -> Didn't change

CodePudding user response:

PDFPage() gives you a default 8.5" x 11.0" page.

You cannot make the .cropBox (or any PDFDisplayBox) larger than the page itself.

If you want to create a different size page, you'll probably want to use UIGraphicsPDFRenderer to create the data, and then PDFDocument(data: theData) to generate the PDF document with the desired page size.

For example:

    let pdfMetaData = [
        kCGPDFContextCreator: "Test Creator",
        kCGPDFContextAuthor: "Test Author"
    ]
    let format = UIGraphicsPDFRendererFormat()
    format.documentInfo = pdfMetaData as [String: Any]
    
    // 1000 x 1000 point-size page
    let pageWidth = 1000
    let pageHeight = 1000
    let pageRect = CGRect(x: 0, y: 0, width: pageWidth, height: pageHeight)
    
    let renderer = UIGraphicsPDFRenderer(bounds: pageRect, format: format)

    let pData = renderer.pdfData { (context) in
        context.beginPage()
        let attributes = [
            NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 40)
        ]
        let text = "1,000 x 1,000 (approx 13.8\" x 13.8\") pdf page"
        text.draw(at: CGPoint(x: 0, y: 0), withAttributes: attributes)
    }
    
    
    if let pdd = PDFDocument(data: pData),
       let pdfPage = pdd.page(at: 0)
    {
        print(pdfPage.bounds(for: .cropBox))
    }
  • Related