是否有可能一個NSattributedString帶附件(RTFD不是RTF)轉換爲ASCII,編輯流,並將其轉換回?到目前爲止,我能夠將RTFD轉換爲String
流。但將其重新轉換爲NSData
對象不起作用。這是我在操場上使用的代碼。可可轉換RTFD爲ASCII和背部
import Cocoa
func stream(attr: NSAttributedString) -> String? {
if let d = attr.rtfd(from: NSMakeRange(0, attr.length), documentAttributes: [NSDocumentTypeDocumentAttribute: NSRTFDTextDocumentType]) {
if let str = String(data: d, encoding: .ascii) { return str }
else {
print("Unable to produce RTFD string")
return nil
}
}
print("Unable to produce RTFD data stream")
return nil
}
if let im = NSImage(named: "image.png") {
let a = NSTextAttachment()
a.image = im
let s = NSAttributedString(attachment: a)
if let str = stream(attr: s) {
print("\(str)\n") //prints a string, which contains RTF code combined with NSTextAttachment string representation
if let data = str.data(using: .ascii) { //this is where things stop working
if let newRTF = NSAttributedString(rtfd: data as Data, documentAttributes: nil) {
print(newRTF)
}
else { print("rtfd was not created") }
}
else { print("could not make data") }
}
}
我錯過了什麼?或者我的整個概念在這裏是錯的?我這樣做是爲了解決OS X處理RTF文檔中附加圖像的限制。
編輯: 我試圖解決的限制是設置圖像的尺寸以RTF流。文本處理系統要求我們使用NSTextAttachment。無論何時粘貼圖像,圖像都會根據像素的高度和寬度自動調整圖像的大小。不幸的是,沒有辦法控制這個屬性。我已嘗試here並且還使用所有技術here。
至於ASCII流,我並不想編輯圖片附件本身。打印流時,實際的RTF代碼可見且可編輯。這是有效的,對於這個限制是一個很好的解決方法。我需要的只是編輯RTF代碼並更改Apple使用的\width
和\height
屬性。
這似乎並不奇怪,這是失敗的,爲什麼會包含圖像的編碼Unicode字符串能夠被無損轉換爲ASCII字符串?目前尚不清楚你在這裏做什麼。你可能會更好地解釋你所關心的任何限制,並尋求指導來解決它。 (您可以編輯問題或者更好地刪除這個問題並創建一個新問題,請不要在評論中解釋。) – CRD
@CRD你好,我已經更新了問題以包含更多信息。如果我在概念上錯過了一些東西,這是一個非常錯誤的方法,那麼我很樂意學習。 – MAH