Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invoking Word for rtf to docx conversion

I have a need to routinely programmatically convert *.rtf files into *.docx. Manually, this works just fine with Save As inside Word 2007 ... the resulting docx behaves just fine. Programmatically, I can't get it to work.

What I tried is basically the following:

Fetch RTF from Word

... but in the reverse direction. Instead of opening *.docx and using SaveAs to *.rtf, I'm opening the *.rtf and using SaveAs to *.docx. However, the resulting file won't open, and so evidently there's something I don't understand. Is

wordApp.Documents.Open(@"D:\Bar\foo.rtf")

not a legit thing to do?

Any thoughts about how to do this would be appreciated.

like image 949
GregA Avatar asked Feb 04 '11 21:02

GregA


3 Answers

You can try this code, it works for me

var wordApp = new Microsoft.Office.Interop.Word.Application();
var currentDoc = wordApp.Documents.Open(@"C:\TestDocument.rtf");
currentDoc.SaveAs(@"C:\TestDocument.doc", Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatDocument97);

I got the same error when I tried to use wdFormatDocument or wdFormatDocumentDefault

EDIT: this is an update to the code, it converts it but u will get the error once then it never appeared again!!

var wordApp = new Microsoft.Office.Interop.Word.Application();
var currentDoc = wordApp.Documents.Open(@"C:\TestDocument.rtf");
currentDoc.SaveAs(@"C:\TestDocument", Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatDocumentDefault);
currentDoc.Close();
wordApp.Quit();
like image 81
Ahmed Magdy Avatar answered Nov 18 '22 05:11

Ahmed Magdy


Can you show the code where you are calling SaveAs? I am curious which Word.WdSaveFormat you are specifying. It sounds like it is saving the rtf data, but changing the extension to .docx.

like image 40
Mark Avenius Avatar answered Nov 18 '22 04:11

Mark Avenius


Here is the code that does conversion. The code is almost the same as shown above, with some small (but important) difference - it is necessary to use references (not objects themselves):

Microsoft.Office.Interop.Word.Application _App = new Microsoft.Office.Interop.Word.Application();
Microsoft.Office.Interop.Word.Document _Doc =  _App.Documents.Open("c:/xxx.rtf");

object _DocxFileName = "C:/xxx.docx";
Object FileFormat = Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatXMLDocument;

_Doc.SaveAs2(ref _DocxFileName, ref FileFormat);
like image 2
Alex Avatar answered Nov 18 '22 04:11

Alex