How to render an entire tableview into a PDF

I'm trying to turn a tableview into a PDF file. This is some sample code:

Code Block
let data = NSMutableData()
let frame = CGRect(origin: .zero, size: tableView.contentSize)
UIGraphicsBeginPDFContextToData(data, frame, nil)
UIGraphicsBeginPDFPage()
guard let context = UIGraphicsGetCurrentContext() else { return nil }
let numScreens = Int(tableview.contentSize.height / tableView.frame.size.height)
let height = Int(tableView.frame.size.height)
for i in 0...numScreens {
let offset = CGPoint(x: 0, y: i * height)
tableView.setContentOffset(offset, animated: false)
tableView.layer.render(in: context)
}
UIGraphicsEndPDFContext()

As you can see I move the tableview one screen height at a time by setting its contentOffset and render the layer into the pdf each time.

This works for 90% of cases, but when the tableview is on the longer side it will have random stretches of whitespace in the PDF. The tableview consists of UILabel, UITextView with attributedLabels, and UIImage. Usually UITextView's are what are replaced with whitespace.

I think that this used to work and recently started failing.
Post not yet marked as solved Up vote post of battman Down vote post of battman
175 views