Search code examples
c#ms-wordcomoffice-interopadd-in

SaveCopyAs behavior in Microsoft Word


As everybody knows, Word do not provide SaveCopyAs like PowerPoint or Excel. I tried different approaches, but without a satisfying result.

I'm able to copy the document on the fly either with correct formatting (positioning of elements -> wdPasteDefault) or correct styles (font and colors -> wdPasteDefault).

If the user close the original document he must be asked if the document should be saved and select a path.

For now I have tried the different approaches on Word 2016. Finally I want to support 2010 to 2016.

One approach was:

        object wdWhat = Microsoft.Office.Interop.Word.WdGoToItem.wdGoToPage;
        object wdWhich = Microsoft.Office.Interop.Word.WdGoToDirection.wdGoToAbsolute;

        Microsoft.Office.Interop.Word.Range range = document.Range(ref missObj, ref missObj);
        Microsoft.Office.Interop.Word.Range pageRange = document.Range(ref missObj, ref missObj);

        pageRange.Start = range.GoTo(ref wdWhat, ref wdWhich, ref missObj, ref missObj).Start;
        pageRange.End = document.Range(ref missObj, ref missObj).End;
        pageRange.Copy();

        Microsoft.Office.Interop.Word.Document newDoc = AddinModule.CurrentInstance.WordApp.Documents.Add(ref missObj, ref missObj, ref missObj, ref missObj);

        newDoc.PageSetup.PageWidth = document.PageSetup.PageWidth;
        newDoc.PageSetup.PageHeight = document.PageSetup.PageHeight;
        AddinModule.CurrentInstance.WordApp.Selection.PasteAndFormat(Microsoft.Office.Interop.Word.WdRecoveryType.wdPasteDefault);

        object newDocName = filePath;
        newDoc.SaveAs(ref newDocName, ref missObj, ref missObj, ref missObj, ref missObj, ref missObj, ref missObj, ref missObj, ref missObj, ref missObj, ref missObj, ref missObj, ref missObj, ref missObj, ref missObj, ref missObj);
        object saveChanges = WdSaveOptions.wdSaveChanges;
        ((Microsoft.Office.Interop.Word._Document)newDoc).Close(saveChanges, ref missObj, ref missObj);
        Marshal.ReleaseComObject(newDoc);
        newDoc = null;

Solution

  • There is a well-known solution with IPersistFile, maybe it's good enough for you:

    using System.Runtime.InteropServices.ComTypes;
    
    var f = (IPersistFile)doc;
    f.Save("[path]", false);