简体   繁体   中英

converting html to image in ios

I am using multiple .html files in my app and opens it in a webview , i need to show the html pages as a thumb view as well , is it possible to convert the html pages into images or any other methods to show the html files as a preview. Please help me if any one know

-(void) webViewDidFinishLoad:(UIWebView *)webView { 

UIGraphicsBeginImageContext(CGSizeMake(webView.layer.frame.size.width, webView.layer.frame.size.height));
[webView.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();


UIGraphicsBeginImageContext(CGSizeMake(70,100));
[image drawInRect:CGRectMake(0, 0, 70,100)];
image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

//image is now a 70x100 thumbnail. make sure you include CoreGraphics
}

WKWebView has a more convenient way of doing it these days

class WebviewDelegate: NSObject, WKNavigationDelegate {

    var completion: ((UIImage?) -> ())?

    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        webView.evaluateJavaScript("document.body.offsetHeight;") { (result, error) in
            if let height = result as? CGFloat {
                let config = WKSnapshotConfiguration()
                config.rect = CGRect(x: 0, y: 0, width: webView.scrollView.contentSize.width, height: height)

                webView.takeSnapshot(with: config) { (image, error) in
                    self.completion?(image)
                }
            }
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM