7

I want to convert a NSAttributedString to HTML string. I've been searching how to solve it, but I have no results yet.

Any idea how can I do it?

Charles Lima
  • 381
  • 4
  • 9
  • 4
    possible duplicate of [How do i convert NSAttributedString into HTML string?](http://stackoverflow.com/questions/5298188/how-do-i-convert-nsattributedstring-into-html-string) – Larme Sep 25 '15 at 14:07

2 Answers2

3
let attrStr = NSAttributedString(string: "Hello World")
let documentAttributes = [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType]
do {
    let htmlData = try attrStr.dataFromRange(NSMakeRange(0, attrStr.length), documentAttributes:documentAttributes)
    if let htmlString = String(data:htmlData, encoding:NSUTF8StringEncoding) {
        print(htmlString)
    }
}
catch {
    print("error creating HTML from Attributed String")
}

you can use this code .it's swift example

3

that can be wrapped in an own extension for NSAttributedString

// swift 5.2 

import Foundation

extension NSAttributedString {
    func toHtml() -> String? {
        let documentAttributes = [NSAttributedString.DocumentAttributeKey.documentType: NSAttributedString.DocumentType.html]
        do {
            let htmlData = try self.data(from: NSMakeRange(0, self.length), documentAttributes:documentAttributes)
            if let htmlString = String(data:htmlData, encoding:String.Encoding.utf8) {
                return htmlString
            }
        }
        catch {
            print("error creating HTML from Attributed String")
        }
        return nil
    }
}
5422m4n
  • 790
  • 5
  • 12