我花了好几天的时间寻找将带有附件的属性字符串放到 NSPasteboard 上的解决方案。
我可以读取带有附件的 RTFD 文件,修改其文本和属性,然后将其粘贴在 NSPasteboard 上以用于其他应用程序(例如 Mail.app),并且效果很好。但我想做的也是在文本中的某个位置添加图像。我可以将文本作为属性字符串来做到这一点,但是如果我尝试插入图像(作为属性字符串的附件),图像永远不会到达(尽管其余的会)。
RTFD似乎有多种风格,我认为我需要的一种是序列化的。我已经尝试了许多 NSPasteboard 声明类型的变体,甚至使用 FileWrappers,但一定缺少一些重要的东西。不管我做什么,执着似乎永远不会到来。
奇怪的是,如果我读取一个带有图像附件的 RTFD 文件,对其进行修改并将其粘贴到粘贴板上,这些原始附件可以正常工作——如果我尝试添加新附件,它们就不会成功。一个例子是读取一个 RTFD 文件,处理它,加载粘贴板,然后将结果粘贴到邮件中。所有原始文本和图像,以及任何新修改或添加的文本和属性都会显示出来,但只是缺少附加的图像。
这是一些示例代码:
用一些文本创建一个属性字符串,然后添加一个附加的图像,然后再添加一点文本,在 textView 中显示它(所有这些都可以),然后加载粘贴板并粘贴到 textEdit 或 Mail ......附加的图像不存在,但其余的是:
// get the image
NSImage *myImage = [[NSImage alloc] initWithData: [window dataWithPDFInsideRect:[theImage frame]]];
// set the image as an attachment
NSTextAttachment *myAttachment = [[NSTextAttachment alloc] init];
NSTextAttachmentCell *myAttachmentCell = [[NSTextAttachmentCell alloc] initImageCell:myImage];
[myAttachment setAttachmentCell:myAttachmentCell];
// put image inside attributed string
NSAttributedString *myImageString = [NSAttributedString attributedStringWithAttachment:myAttachment] ;
// make an attributes dictionary (simply makes text blue) as an example
NSDictionary *myAttributesDict = [NSDictionary dictionaryWithObjectsAndKeys:
[NSColor blueColor], NSForegroundColorAttributeName,
nil];
// and add some beginning text
NSMutableAttributedString *theCombinedString = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"Here's an image we just grabbed: \n\n"] attributes:myAttributesDict];
// now append our attached image
[theCombinedString appendAttributedString:myImageString];
// and add some following text as an example
NSMutableAttributedString *endString = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"\n\n How about that!\n"] attributes:myAttributesDict];
// and stick it all together
[theCombinedString appendAttributedString: endString];
// now display it in a textView to make sure we have something
[[junkTextView textStorage] appendAttributedString: theCombinedString];
/// --- works just fine to here --- ///
// the following loads the pastboard, including the added text, but for some reason, leaves out the above attachment
NSPasteboard *thePboard = [NSPasteboard generalPasteboard];
[thePboard clearContents];
NSAttributedString *theContents = [[NSAttributedString alloc] theCombinedString ];
[thePboard writeObjects:[NSArray arrayWithObject:theContents]];
// pasting into mail or textEdit shows the above before and after text, but not the image.
有任何想法吗?
我尝试过使用 NSData、NSFileWrapper 序列化、设置各种粘贴板类型等等。到目前为止,似乎没有任何效果。如果我将图像加载为 TIFF 数据,它可以很好地粘贴,但我需要将其作为属性字符串插入到已经有附件的文件中的更大字符串中。
这是我第一次在这里发帖,所以请原谅任何格式错误 - 我会学习,非常感谢任何指示或帮助,即使它是 RTFM,我已经这样做但可能误解了。