Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

To Convert HTML doc to image in cocoa

Tags:

objective-c

is it possible to convert the HTML page to image in cocoa?

Actually i have created the complete view in the HTML and now i want to convert the whole html preview to the image (any jpeg or png etc.).

I couldn't find any resource or sample on the web, which provides some sort of help on my above queries.It's highly appreciated if someone could share his wisdom on how I can achieve this.

Thanks in advance..

like image 633
Vinay Jain Avatar asked May 26 '11 09:05

Vinay Jain


1 Answers

First off, I'd like to thank sergio... his answer got me started but I thought I'd share some of the code that I didn't find obvious that I had to write to make it work:

Here's how to make a thumbnail for a page without ever having it displayed:

// Your width and height can be whatever you like, but if you want this to render
// off screen, you need an x and y bigger than the superview's width and height
UIWebView* webView = [[UIWebView alloc] initWithFrame:CGRectMake(largerScreenDimension, largerScreenDimension, largerScreenDimension, largerScreenDimension)];
[self.view addSubview:webView]; // UIWebViews without an assigned superview don't load ever.
webView.delegate = self; // or whoever you have implement UIWebViewDelegate
webView.scalesToFit = YES; // This zooms the page appropriately to fill the entire thumbnail.
[webView loadRequest:[NSURLRequest requestWithURL:url]];

Then implement this in your delegate:

- (void)webViewDidFinishLoad:(UIWebView *)webView {
    UIGraphicsBeginImageContext(webView.bounds.size);
    [webView.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *webViewImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    NSData *thumbnailData = UIImagePNGRepresentation(webViewImage);
    [webView removeFromSuperview];
}

Finally, to display this thumbnail you'll need something like:

thumbnailImageView.image = [UIImage imageWithData:thumbnailData];

As a bonus thing I'll mention, I wanted multiple thumbnails to be generated at once. I found using objc_setAssociatedObject() and objc_getAssociatedObject() to be very helpful with keeping track of which webView was loading which thumbnail. Going into detail on how that worked is beyond the scope of this question, though.

like image 56
ArtOfWarfare Avatar answered Sep 20 '22 03:09

ArtOfWarfare