Save a string as MS Word docx

asobjc

(Jonas Whale) #1

Is there a method to save a NSString directly as a MS Word XML document (docx)?
All my attempts ended in failure.

Thaaaanks!


(Shane Stanley) #2

You need an NSAttributedString, not an NSString. Then you use docFormatFromRange:documentAttributes:.


(Jonas Whale) #3

The best I can do is:

use framework "Foundation"
use framework "AppKit"
use scripting additions

set theURL to current application's NSURL's fileURLWithPath:((POSIX path of (path to desktop folder)) & "Test.doc")
set attribString to (current application's NSAttributedString's alloc()'s initWithString:"SomeText")
set docAtt to current application's NSDictionary's dictionaryWithObject:(current application's NSDocFormatTextDocumentType) forKey:(current application's NSDocumentTypeDocumentAttribute)
set theData to (attribString's docFormatFromRange:({location:0, |length|:attribString's |length|()}) documentAttributes:docAtt)
(theData's writeToURL:(theURL) atomically:(true))

But it opens in compatibility mode in MSWord… and if saved with docx extension, it won’t open at all.
I tried also with NSWordMLTextDocumentType -> same result.

Where is my mistake?


(Shane Stanley) #4

Instead of NSDocFormatTextDocumentType try NSWordMLTextDocumentType.


(Jonas Whale) #5

Already tried.
All my attempts ends in failure. Even if I pass documentAttributes:(missing value)
:wink: