Convert HTML Content to image

2019-04-11 21:03发布

HTML Content Example : This is HTML Content.<div>This is <b>BOLD</b> text </div><div>This is <i> ITALIC </i> text</div> This is the HTML content which I want to render and place it in a UIImageView and then save this image. I tried to first render that HTML content and generated a PDF and then convert that PDF into Image but that image is of very bad result. So that's why I am finding some thing that render my HTML content and add into UIImageVIew and than I will easily save that image inside my application memory.

2条回答
走好不送
2楼-- · 2019-04-11 21:29

Try this solution using label/UITextView

set html text to your label.

do {
let attrStr = try NSAttributedString(
    data: "<b><i>text</i></b>".data(using: String.Encoding.unicode, allowLossyConversion: true)!,
    options: [ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
    documentAttributes: nil)
yourLabel.attributedText = attrStr
} catch let error {
  print(error)
}

to take snapshot try below code

UIGraphicsBeginImageContextWithOptions(yourLabel.bounds.size, 
false, 0);
yourLabel.drawViewHierarchyInRect(yourLabel.bounds, afterScreenUpdates: true)
let copied = UIGraphicsGetImageFromCurrentImageContext(); // You have to save this content in your internal memory
yourImageView.image = copied // To Preview that Image in your ImageView
UIGraphicsEndImageContext();
查看更多
劫难
3楼-- · 2019-04-11 21:34

I am not sure about this but you can do so something like rendering HTML in the UIWebView. Then take the screenshot via code.

查看更多
登录 后发表回答