Reputation: 21
I'm trying to create an add-in in C# for MS Word 2010 that will add a new ribbon and a click event-handler. This click event-handler should save the active file in c:\temp
, for example. And then I need to load the file content into a byte array.
Probably something like this:
public void ClickEventHandler(Office.IRibbonControl control)
{
string fileLocation = "c:\temp\test.docx";
Word.Document document = this.Document;
document.SaveAs(fileLocation);
byte[] byteArray = File.ReadAllBytes(fileLocation);
}
The point is, this is pseudo-code and I don't know how to load an active document into a byte array. If there is a way without saving the document it would be even better.
And a query if the active file is a docx (and not a doc file) would be nice as well.
Upvotes: 2
Views: 2679
Reputation: 452
Word.Document document = Globals.ThisAddIn.Application.ActiveDocument;
document.SaveAs2(goldenpath + "\\" + name + "." + id + ".docx");
document.Close();
Upvotes: 2
Reputation: 8982
I use this generic function in my program to serialize arbitrary objects to a byte array:
private byte[] MakeByteSize<U>(U obj)
{
if (obj == null) return null;
var bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
var ms = new System.IO.MemoryStream();
bf.Serialize(ms, obj);
return ms.ToArray();
}
Edit:
After reading your additional content, I'm confident that serializing the Word.Document
object won't get you what you need, since the byte array representing that object in the program (which is probably a wrapper around some COM interop) won't be the same as the byte array representing the information stored in the file about the document.
Looking at the MSDN article you referenced, it looks like what we really need is a WordprocessingDoc
instance representing the document that we can pass to the HtmlConverter
class. So I think the question you really want to ask is "How can I create a DocumentFormat.OpenXml.Packaging.WordprocessingDocument
from an open document without saving the file first?"
Unforunately, I'm not sure that's possible since I'm not really spotting any methods on that class that would do that.
On the .doc
vs .docx
issue, the Open XML SDK for Microsoft Office says that it works with documentat that adhere to the "Office Open XML File Formats Specification" which I believe means it will only work with the .docx
file format. You might have to try a different route on this, like exporting to PDF perhaps. Good luck!
Upvotes: 0