Last active
May 19, 2025 02:23
-
-
Save vadimblv/2f56aa858bea73a02728 to your computer and use it in GitHub Desktop.
Rendering UITableView into PDF
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@implementation UITableViewIntoPDF | |
+ (NSData*)pdfDataWithTableView:(UITableView*)tableView { | |
UIGraphicsBeginImageContextWithOptions(tableView.contentSize, NO, 0); | |
[tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] | |
atScrollPosition:UITableViewScrollPositionTop animated:NO]; | |
[tableView.layer renderInContext:UIGraphicsGetCurrentContext()]; | |
int iterationCount = ceil(tableView.contentSize.height / tableView.bounds.size.height); | |
for (int i = 0; i < iterationCount; i++) { | |
[tableView setContentOffset:CGPointMake(0, tableView.bounds.size.height * i)]; | |
[tableView.layer renderInContext:UIGraphicsGetCurrentContext()]; | |
} | |
UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); | |
UIImageView *pdfImage = [[UIImageView alloc] initWithImage:image]; | |
UIGraphicsEndImageContext(); | |
return [self createPDFfromUIView:pdfImage]; | |
} | |
+ (NSData*)createPDFfromUIView:(UIView *)pdfImage { | |
NSMutableData *pdfData = [NSMutableData data]; | |
UIGraphicsBeginPDFContextToData(pdfData, pdfImage.bounds, nil); | |
UIGraphicsBeginPDFPage(); | |
CGContextRef pdfContext = UIGraphicsGetCurrentContext(); | |
[pdfImage.layer renderInContext:pdfContext]; | |
UIGraphicsEndPDFContext(); | |
return pdfData; | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
9 years old!!, and still works thanks a lot.