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?
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?
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
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
}
}