I came up with another solution:
-(NSData*)pdfDataFromTableViewContent{ NSMutableData *pdfData = [NSMutableData data]; //The real size, not only the visible part CGSize contentSize = self.tableView.contentSize; CGRect tableViewRealFrame = self.tableView.frame; //Size tableView to show the whole content self.tableView.frame = CGRectMake(0, 0, contentSize.width, contentSize.height); //Generate PDF (one page) UIGraphicsBeginPDFContextToData(pdfData,self.tableView.frame, nil); UIGraphicsBeginPDFPage(); [self.tableView.layer renderInContext:UIGraphicsGetCurrentContext()]; UIGraphicsEndPDFContext(); //Resize frame self.tableView.frame = tableViewRealFrame; return pdfData;}
Position the frame so that it matches the entire contents of the scrollView, capture it in a graphicsContext, resize the frame.
The top code generates one page.
For more pages, I mainly use this:
//MultiPage CGRect mediaBox = self.tableView.frame; CGSize pageSize = CGSizeMake(self.view.frame.size.width, 800); UIGraphicsBeginPDFContextToData(pdfData, CGRectZero, nil); CGContextRef pdfContext = UIGraphicsGetCurrentContext(); NSInteger currentPage = 0; BOOL done = NO; do { UIGraphicsBeginPDFPageWithInfo(CGRectMake(0, 0.0, pageSize.width, pageSize.height), nil); CGContextTranslateCTM(pdfContext, 0, -(pageSize.height*currentPage)); [self.view.layer renderInContext:pdfContext]; if ((pageSize.height*(currentPage+1)) > mediaBox.size.height) done = YES; else currentPage++; } while (!done); UIGraphicsEndPDFContext();
source share