Skip to content

Instantly share code, notes, and snippets.

@chrisvasselli
Created September 14, 2021 00:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chrisvasselli/d8e4e1bf987e6885d02104b1990d4978 to your computer and use it in GitHub Desktop.
Save chrisvasselli/d8e4e1bf987e6885d02104b1990d4978 to your computer and use it in GitHub Desktop.
Create full page screenshots from a table view controller
import Foundation
import UIKit
extension UITableViewController: UIScreenshotServiceDelegate {
public func screenshotService(_ screenshotService: UIScreenshotService, generatePDFRepresentationWithCompletion completionHandler: @escaping (Data?, Int, CGRect) -> Void) {
let originalFrame = tableView.frame
let originalContentOffset = tableView.contentOffset
// Layout into an extra large frame, to force the actual heights to be calculated for all rows with estimated heights
let oversizedContentSize = CGSize(width: tableView.contentSize.width, height: 100000)
tableView.frame = CGRect(origin: .zero, size: oversizedContentSize)
tableView.layoutIfNeeded()
let actualContentSize = tableView.contentSize
let data = NSMutableData()
UIGraphicsBeginPDFContextToData(data, .zero, nil)
UIGraphicsBeginPDFPageWithInfo(CGRect(origin: .zero, size: actualContentSize), nil)
if let context = UIGraphicsGetCurrentContext() {
tableView.contentOffset = .zero
tableView.frame = CGRect(origin: .zero, size: actualContentSize)
tableView.layoutIfNeeded()
tableView.layer.render(in: context)
}
else {
completionHandler(nil, 0, .zero)
}
UIGraphicsEndPDFContext()
tableView.frame = originalFrame
tableView.contentOffset = originalContentOffset
let offsetInPDF = actualContentSize.height - originalContentOffset.y - originalFrame.height
completionHandler(data as Data, 0, CGRect(origin: CGPoint(x: 0, y: offsetInPDF), size: self.view.frame.size))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment