我正在尝试将NSAttributedString
保存到服务器,并在需要时将其所有属性取回
一个小时的搜索后,我找到了这段代码
extension NSAttributedString {
var toHTML: String {
let documentAttributes = [NSAttributedString.DocumentAttributeKey.documentType: NSAttributedString.DocumentType.html]
do {
let htmlData = try self.data(from: NSRange(location: 0, length: 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 ""
}
return ""
}
extension String {
var fromHTML: NSAttributedString {
guard let data = data(using: .utf8) else { return NSAttributedString() }
do {
return try NSAttributedString(data: data, options: [NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.html, .characterEncoding: String.Encoding.utf8.rawValue], documentAttributes: nil)
} catch {
return NSAttributedString()
}
}
当我需要将NSAttributedString
转换为HTML格式时,它就正确了
"<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\">\n<html>\n<head>\n<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">\n<meta http-equiv=\"Content-Style-Type\" content=\"text/css\">\n<title></title>\n<meta name=\"Generator\" content=\"Cocoa HTML Writer\">\n<style type=\"text/css\">\np.p1 {margin: 0.0px 0.0px 0.0px 0.0px; font: 20.0px Palatino}\nspan.s1 {font-family: \'Palatino\'; font-weight: bold; font-style: normal; font-size: 20.00pt}\n</style>\n</head>\n<body>\n<p class=\"p1\"><span class=\"s1\">Hello world</span></p>\n</body>\n</html>\n"
但是当我尝试将其格式化为NSAttributedString
时,它会更改字体的实际大小
Hello world{
NSColor = "kCGColorSpaceModelRGB 0 0 0 1 ";
NSFont = "<UICTFont: 0x121d04440> font-family: \"Palatino\"; font-weight: bold; font-style: normal; font-size: 26.67pt";
NSKern = 0;
NSParagraphStyle = "Alignment 4, LineSpacing 0, ParagraphSpacing 0, ParagraphSpacingBefore 0, HeadIndent 0, TailIndent 0, FirstLineHeadIndent 0, LineHeight 31/0, LineHeightMultiple 0, LineBreakMode 0, Tabs (\n), DefaultTabInterval 36, Blocks (\n), Lists (\n), BaseWritingDirection 0, HyphenationFactor 0, TighteningForTruncation NO, HeaderLevel 0";
NSStrokeColor = "kCGColorSpaceModelRGB 0 0 0 1 ";
NSStrokeWidth = 0;
}
我在这里做错什么了?。