sgr-ksmt / PDFGenerator

A simple generator of PDF written in Swift.
MIT License
755 stars 110 forks source link

Autolayouts and constraints do not render on PDF #106

Open AmishaChordia opened 5 years ago

AmishaChordia commented 5 years ago

Any constraints on the subviews do not render as expected on the PDF; I have to use frames to arrange my views instead of autolayouts. Is there a way I can have the applied constraints be visible on the PDF?

example:


@objc @IBAction fileprivate func generateSamplePDFFromViews(_ sender: AnyObject?) {
        let superView = UIView(frame: CGRect(x: 0, y: 0, width: PDFPageSize.A4.width, height: PDFPageSize.A4.height))
        superView.backgroundColor = UIColor.green

        let subview = UIView(frame: CGRect.zero)
        subview.translatesAutoresizingMaskIntoConstraints = false
        superView.addSubview(subview)
        subview.backgroundColor = UIColor.red
        if #available(iOS 9.0, *) {
            NSLayoutConstraint.activate([
                subview.rightAnchor.constraint(equalTo: superView.rightAnchor),
                subview.bottomAnchor.constraint(equalTo: superView.bottomAnchor),
                subview.widthAnchor.constraint(equalToConstant: 50),
                subview.heightAnchor.constraint(equalToConstant: 90)
                ])
        } else {
            // Fallback on earlier versions
        }

        do {
            let dst = getDestinationPath(1)
            if outputAsData {
                let data = try PDFGenerator.generated(by: [superView])
                try data.write(to: URL(fileURLWithPath: dst))
            } else {
                try PDFGenerator.generate([superView], to: dst)
            }
            openPDFViewer(dst)
        } catch let e {
            print(e)
        }
    }

The subview in the above code is never rendered on pdf

ArkadiYoskovitz commented 5 years ago

Try triggering a layout pass before the pdf render call.

Use setNeedsLyout & layoutIfNeeded