Rajesh Loganathan
Rajesh Loganathan

Reputation: 11227

How to create thumbnail image for document(doc, html) loaded in UIWebView in iOS

1.First ViewController in Tableview

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([FileType isEqualToString:@"jpg"])
    {
        cell.imageView.image =[UIImage imageNamed:[NSString stringWithFormat:@"%@.jpg",[FilelistArray objectAtIndex:indexPath.row]]];
    }
    else if ([FileType isEqualToString:@"doc"])
    {
        cell.imageView.image = ??????
    }
}

2.Second ViewController..

- (void)viewDidLoad
{
    [super viewDidLoad];
    NSURL *targetURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"FileName" ofType:@"doc"]];
    NSURLRequest *request = [NSURLRequest requestWithURL:targetURL]             
    WebView.delegate = self;
    [WebView setScalesPageToFit:YES];
    CGFloat contentHeight = WebView.scrollView.contentSize.height;
    [WebView loadRequest:request];
    [self.view addSubview:WebView];
}

Output:

enter image description here

Upvotes: 1

Views: 3614

Answers (1)

Matías R
Matías R

Reputation: 2195

You can load the content in the UIWebView and capture it with:

- (UIImage*)screenshot:(UIView*)theView
{
    UIGraphicsBeginImageContext(theView.bounds.size);
    [theView.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return img;
}

Store the image returned and use it as a thumbnail. You can generate it the first time the user views the document (in which case the first time the user sees the list the thumbnail won't be available) or generate them all in the view controller with the table view. For this second option, you'd have to create a UIWebView and put it out of the frame of the superview, where it's not visible, and then capture it.

Now that I'm thinking, maybe there's another option... simply use a small UIWebView instead of an image in the case the document is not an image, and load the document. It should appear small on the cell. Just make sure to set scalesPageToFit to YES.

EDIT:

I quickly tried my last suggestion and it worked. I created a UIViewController with a UITableView, a cell that has a UIWebView inside with tag 1000. Then I do:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"webViewTableCell"];

    UIWebView *wv = (UIWebView *)[cell viewWithTag:1000];
    wv.scalesPageToFit = NO;
    wv.userInteractionEnabled = NO;
    [wv loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://studentaid.ed.gov/sites/default/files/public-service-employment-certification-form.pdf"]]];

    return cell;
}

It loads a random PDF from the internet and displays it as a thumbnail:

enter image description here

Upvotes: 3

Related Questions