vin vin - 2 months ago 6
iOS Question

How to get a snapshot of UITableView in a PDF format

I have a

UITableView
which is populated with some data but since it contains data that is more cells than the viewable area of the screen, I only managed to get only the snapshot of it, I want to know if there is any other way I can get the whole tableview snapshot in pdf..this is what I have tried thanks

- (IBAction)clickMe:(id)sender
{
UIView *viewToRender = self.myTableView;
CGPoint contentOffset = self.myTableView.contentOffset;

UIGraphicsBeginImageContext(viewToRender.bounds.size);

CGContextRef ctx = UIGraphicsGetCurrentContext();

// KEY: need to translate the context down to the current visible portion of the tablview
CGContextTranslateCTM(ctx, 0, -contentOffset.y);

[viewToRender.layer renderInContext:ctx];

UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIImageView *myImage=[[UIImageView alloc]initWithImage:image];

UIGraphicsEndImageContext();

[self createPDFfromUIViews:myImage saveToDocumentsWithFileName:@"PDF Name"];

}



- (void)createPDFfromUIViews:(UIView *)myImage saveToDocumentsWithFileName:(NSString *)string
{
NSMutableData *pdfData = [NSMutableData data];

UIGraphicsBeginPDFContextToData(pdfData, myImage.bounds, nil);
UIGraphicsBeginPDFPage();
CGContextRef pdfContext = UIGraphicsGetCurrentContext();


// draws rect to the view and thus this is captured by UIGraphicsBeginPDFContextToData

[myImage.layer renderInContext:pdfContext];

// remove PDF rendering context
UIGraphicsEndPDFContext();
NSArray* documentDirectories = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES);

NSString* documentDirectory = [documentDirectories objectAtIndex:0];
NSString* documentDirectoryFilename = [documentDirectory stringByAppendingPathComponent:string];

NSLog(@"%@",documentDirectoryFilename);
[pdfData writeToFile:documentDirectoryFilename atomically:YES];
}

vin vin
Answer
UIGraphicsBeginImageContext(self.myTableView.contentSize);
[self.myTableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:NO];
[self.myTableView.layer renderInContext:UIGraphicsGetCurrentContext()];

int rows = [self.myTableView numberOfRowsInSection:0];
int numberofRowsInView = 4;
for (int i =0; i < rows/numberofRowsInView; i++) {
    [self.myTableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:(i+1)*numberofRowsInView inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:NO];
    [self.myTableView.layer renderInContext:UIGraphicsGetCurrentContext()];

}
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIImageView *myImage=[[UIImageView alloc]initWithImage:image];
UIGraphicsEndImageContext();


[self createPDFfromUIViews:myImage saveToDocumentsWithFileName:@"PDF Name"];

i dont know but this code works like a charm for me..