muyexi
6/2/2015 - 8:39 AM

snapshot webview http://stackoverflow.com/a/6950666/2122622

- (UIImage *)snapshot {
    int webViewHeight = [self stringByEvaluatingJavaScriptFromString:@"document.body.offsetHeight;"].floatValue;

    CGFloat pageHeight = self.frame.size.height;
    int pageCount = webViewHeight / pageHeight;
    if ((webViewHeight % pageCount) > 0) {
        pageCount++;
    }

    for (int i = 0; i < pageCount; i++) {
        UIImage *image;
        @autoreleasepool {
            UIGraphicsBeginImageContextWithOptions(self.frame.size, YES, 2.0);
            [self.layer renderInContext:UIGraphicsGetCurrentContext()];
            image = UIGraphicsGetImageFromCurrentImageContext();
            UIGraphicsEndImageContext();

            NSData *imageData = UIImageJPEGRepresentation(image, 0.0);
            NSString *imageName = [NSString stringWithFormat:@"image%i.jpg", i];
            NSString *filePath = [NSTemporaryDirectory() stringByAppendingPathComponent:imageName];
            [imageData writeToFile:filePath atomically:YES];
            
            CGPoint nextPoint = CGPointMake(0, pageHeight * (i + 1));
            [self.scrollView setContentOffset:nextPoint];
            
            image = nil;
            imageData = nil;
        }
    }

    UIImage *completeImage;
    @autoreleasepool {
        CGSize completeImageSize = CGSizeMake(self.scrollView.contentSize.width * 2, 40000);
        UIGraphicsBeginImageContextWithOptions(completeImageSize, YES, 1.0);
        for (int i = 0; i < pageCount; i++) {
            NSString *imageName = [NSString stringWithFormat:@"image%i.jpg", i];
            NSString *filePath = [NSTemporaryDirectory() stringByAppendingPathComponent:imageName];
            UIImage *pageImage = [UIImage imageWithContentsOfFile:filePath];

            CGFloat pageImageHeight = pageHeight * 2;
            CGPoint imagePoint = CGPointMake(0, pageImageHeight * i);
            [pageImage drawAtPoint:imagePoint];

            pageImage = nil;
        }
        completeImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
    }

    return completeImage;
}