html - 从 HTML 转换为 NSAttributedString 错误的属性
问题描述
我正在尝试将 a 保存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()
}
}
当我需要将 a 转换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;
}
我在这里做错了什么?
解决方案
推荐阅读
- java - 创建 bmi 计算器时出错
- javascript - 标签颜色与背景颜色相同 - ChartJS
- r - 如何将 R 的 S3 类与参数一起使用?
- visual-studio-code - 如何限制我的 VS Code 扩展的 VS Code 引擎最低版本?
- assembly - 'imul' 的操作数大小不匹配
- scala - 如何从响应中获取价值?
- python - 无法修复“ValueError:未正确调用 DataFrame 构造函数!”
- c++ - 尽管已安装,但在 MinGW 中找不到 gtkmm
- python - 如何删除矩阵中的一些条目。我正在从 matlab 转换为 python
- windows - 显示 GetInvalidFileNameChars() 的 Powershell 输出的十六进制值