Jojo Narte
Jojo Narte

Reputation: 3104

Resizing/Scaling PDF Pages when converting each UIView into NSMutableData

I have this simple function that accepts an array of UIViews which are of the same sizes which basically could accept either large or smaller views. Then the function would be responsible for scaling each UIView into a 612 x 792 dimensions.

How could I achieve this with proper view scaling? What I have right now would just simply insert the views into the 612 x 792 pdf pages which results into each UIViews getting clipped on the right side.

Here is the code:

func resize(pages: [UIView]) -> NSMutableData {
    let a4 = CGSize(width: 612, height: 792)

    let pdfData = NSMutableData()
    UIGraphicsBeginPDFContextToData(pdfData, CGRect(x:0, y:0, width:a4.width, height: a4.height), nil)
    for _view in pages {
        if let view = _view as? UIView {
            UIGraphicsBeginPDFPageWithInfo(view.bounds, nil)
            UIGraphicsGetCurrentContext()!.saveGState()

            let pdfContext = UIGraphicsGetCurrentContext()!
            view.layer.render(in: pdfContext)
            UIGraphicsGetCurrentContext()!.restoreGState()
        }

    }

    UIGraphicsEndPDFContext()

    return pdfData
}

Upvotes: 1

Views: 196

Answers (0)

Related Questions