微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

ios – 如何以PDF格式获取UITableView的快照

我有一个UITableView,其中填充了一些数据但由于它包含的数据比屏幕的可视区域更多,我只能设法得到它的快照,我想知道是否还有其他方法我可以以PDF格式获取整个tableview快照.这是我尝试过的感谢
- (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,-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];
}

解决方法

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"];

我不知道,但这段代码对我来说就像一个魅力..

原文地址:https://www.jb51.cc/iOS/335341.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐