将NSAttributedString转换为不带CSS的HTML字符串

3

我正在尝试将HTML转换为NSAttributedString格式,然后再转回去。从HTML转换很好,但是转回HTML时,得到的格式无法发送到我们的后端:

<!DOCTYPE html PUBLIC -//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta http-equiv=Content-Style-Type" content="text/css">
<title></title>
<meta name="Generator" content="Cocoa HTML Writer">
<style type="text/css">
p.p1 {margin: 0.0px 0.0px 0.0px 0.0px; line-height: 15.0px; font: 16.0px 'Times New Roman'; color: #000000; -webkit-text-stroke: #000000}
span.s1 {font-family: 'Times New Roman'; font-weight: normal; font-style: normal; font-size: 16.00pt; font-kerning: none}
span.s2 {font-family: 'TimesNewRomanPS-BoldMT'; font-weight: bold; font-style: normal; font-size: 16.00pt; font-kerning: none}
span.s3 {font-family: 'TimesNewRomanPS-ItalicMT'; font-weight: normal; font-style: italic; font-size: 16.00pt; font-kerning: none}
span.s4 {font-family: 'TimesNewRomanPS-BoldItalicMT'; font-weight: bold; font-style: italic; font-size: 16.00pt; font-kerning: none}
</style>
</head>
<body>
<p class="p1"><span class="s1">vanlig text </span><span class="s2">bold</span><span class="s1"> </span><span class="s3">italic</span><span class="s1"> </span><span class="s4">bold_italic asd</span></p>
</body>
</html>

我需要发送给服务器的字符串/格式不能包含CSS,需要更像这样:(不带CSS)

<html>
<body>
<p>vanlig text <b>bold</b> <i>italic</i><b><i>bold_italic asd</i></b>
</p>
</body>
</html>

我将尝试将此解决方案翻译为中文,但未获得成功:NSAttribute string to HTML。我使用css保留了格式。
迄今为止我的代码如下:
extension NSAttributedString
{
    var htmlString : String
    {
        let documentAttributes = [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType]
        if let htmlData = try? self.dataFromRange(NSMakeRange(0, self.length), documentAttributes:documentAttributes),
           let htmlString = String(data:htmlData, encoding:NSUTF8StringEncoding) {
            return htmlString
        }
        return ""
    }

    func attributedStringWithNoTrailingNewLines() -> NSMutableAttributedString
    {
        let mutableAttributedString = NSMutableAttributedString(attributedString: self)
        let nsString = string as NSString
        let lastWhitespaceOrNewlineRange = nsString.rangeOfCharacterFromSet(NSCharacterSet.whitespaceAndNewlineCharacterSet(), options: .BackwardsSearch)
        if lastWhitespaceOrNewlineRange.length != 0 && NSMaxRange(lastWhitespaceOrNewlineRange) == self.length
        {
            mutableAttributedString.replaceCharactersInRange(lastWhitespaceOrNewlineRange, withString: "")
        }
        return mutableAttributedString
    }
}

extension String
{
    var attributedString : NSAttributedString?
    {
        if let data = self.dataUsingEncoding(NSUTF8StringEncoding) {
            let options = [NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType]
            let attrStr = try? NSAttributedString(data: data, options: options, documentAttributes: nil)
            return attrStr
        }
        return nil
    }
}

请查看此链接 http://stackoverflow.com/questions/37915304/html-string-convert-into-attributed-string-with-u00002028-n-ios/37916078#37916078。希望它能对我们有所帮助。 - HariKrishnan.P
1
问题:您的服务器可以管理哪些标签?因为在您的示例中,您只给出了“简单的”标签:<b><i>等。如果仅限于某些标签,您可以列举具有有效范围的属性,并自行添加标签,如有必要,请不要忘记添加“开始”<html><body>`和相应的结束标签。 - Larme
2
你能够做到吗? - emreoktem
如果您已经解决了这个问题,能否请您发布一下代码? - Mehul Thakkar
在下面作为答案添加了一些代码。 - Sunkas
显示剩余2条评论
2个回答

2

我没有用来解决它的确切代码,但我通过迭代nsfontattributes并手动添加支持的html标签来解决了它。在NSAttributedString扩展中类似于这样:

enumerateAttribute(NSFontAttributeName, inRange: NSMakeRange(0, length), options: NSAttributedStringEnumerationOptions(rawValue: 0)) { (value, range, stop) in
    if let font = value as? UIFont {
        var stringInRange = string.substringInRange(range)
        if font.isBold {
            stringInRange = "<b>\(stringInRange)</b>"
        }
        if font.isItalic {
            stringInRange = "<i>\(stringInRange)</i>"
        }
        // ...
    }
}

但如果有复杂的HTML呢? - Mehul Thakkar
1
也许我在问题中没有明确说明,但该应用程序仅支持有限数量的HTML功能,例如加粗、斜体、编号列表和项目符号列表。 - Sunkas

1
我有一种好方法将NSAttributedString转换为HTML字符串,无需CSS。
1)使用UIWebView和UITextView。
2)在WebView中设置您的属性字符串。
[webView loadHTMLString:[yourAttributedString stringByReplacingOccurrencesOfString:@"\n" withString:@"<br/>"] baseURL:nil];

从 UIWebView 中获取你的 HTML 字符串。保留 HTML 标签,不进行解释。
NSString *strExclusion = [webView stringByEvaluatingJavaScriptFromString:@"document.body.innerHTML"];

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接