Skip to content

Instantly share code, notes, and snippets.

@aaronwardle
Created November 7, 2017 20:14
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 aaronwardle/69fe270b98470b43f71eb3667750e933 to your computer and use it in GitHub Desktop.
Save aaronwardle/69fe270b98470b43f71eb3667750e933 to your computer and use it in GitHub Desktop.
Generates a PDF from tableview
if #available(iOS 10.0, *) {
let priorBounds = tableView.bounds
let fittedSize = tableView.sizeThatFits(CGSize(width:priorBounds.size.width, height:tableView.contentSize.height))
tableView.bounds = CGRect(x:0, y:0, width:fittedSize.width, height:fittedSize.height)
let pdfPageBounds = CGRect(x:0, y:0, width:tableView.frame.width, height:self.view.frame.height)
let dir = FileManager.default.urls(for: FileManager.SearchPathDirectory.cachesDirectory, in: FileManager.SearchPathDomainMask.userDomainMask).first!
let fileurl = dir.appendingPathComponent("test.pdf")
//let renderer = UIGraphicsPDFRenderer(bounds: self.view.bounds)
let renderer = UIGraphicsPDFRenderer(bounds: pdfPageBounds)
var pageOriginY: CGFloat = 0
try! renderer.writePDF(to: fileurl, withActions: { (context) in
while pageOriginY < fittedSize.height {
context.beginPage(withBounds: pdfPageBounds, pageInfo: [:])
self.view.drawHierarchy(in: pdfPageBounds, afterScreenUpdates: true)
pageOriginY += pdfPageBounds.size.height
}
})
tableView.bounds = priorBounds
print("test")
} else {
// Fallback on earlier versions
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment