Cocoa 将 RTFD 转换为 ASCII 并返回

Cocoa Converting RTFD to ASCII and back

是否可以将带有附件(RTFD 而非 RTF)的 NSattributedString 转换为 ASCII,编辑流,然后将其转换回来?到目前为止,我能够将 RTFD 转换为 String 流。但是将它变回 NSData 对象是行不通的。这是我在操场上使用的代码。

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 and also using all the techniques here

就 ASCII 流而言,我并没有尝试编辑图像附件本身。打印流时,实际的 RTF 代码是可见和可编辑的。这行得通,并且是解决此限制的一个很好的解决方法。我只需要编辑 RTF 代码并更改 Apple 使用的 \width\height 属性。

在你编辑之后我可以看到你正在尝试做什么,有趣的想法,但它行不通 - 至少不容易。

看看 d 的值,它 不是 存储为 Data 类型值的 ASCII 字符串(或 NSData).它是多个项目的序列化表示; RTF 流(文本),图像数据(二进制)。如果将其转换为 ASCII 字符串并再次转换回来,它将无法正常工作,除非对其进行编码(例如 base 64 编码),否则不能将任意二进制数据表示为 ASCII。

现在您可以尝试以稍微不同的方式进行尝试,跳过转换为 ASCII 并直接编辑 Data 值。这当然是可能的,但是当你编辑一种你不知道的格式(序列化表示)时,你必须小心......即使你成功编辑了表示,也不能保证转换回 NSAttributedString 加上 NSTextAttachment 将保留您的编辑。

我建议你换个方式解决这个问题。您有一个 NSAttributedString 并且您不喜欢将其写入文件后生成的 RTF。因此,在编写 RTF 后对其进行编辑,例如打开 RTFD 包,打开包含的 RTF 文件 (TXT.rtf),编辑它,写回它。

HTH