简体   繁体   中英

Is it possible to save a word document by bypassing the Save or SaveAs methods c#

I have a MS Word AddIn that launches a winform which allows the user to specify some additional metadata which is then saved as an xml file along with a copy of the document in a specified location.

This all works fine when run from a standalone Word document, however one of the areas this will be used is where a Word document is launched inside an application (EMIS WEB). It launches a copy of Word from the local machine which is fine as it allows the AddIn to be run.

When I try to save the document I get a Command Failed. error. The XML file saves no problem: xml.Save(path + docName + ".xml"); .

The application prompts with it's own 'save' like dialog.

“保存”对话框

At first I thought it was the application removing focus from the document therefore this.Application.ActiveDocument.SaveAs failing because it wasn't the Active Document. So I tried getting the Document object when it was active and passing it through to the saveDoc method so that I could set it as the Active Document like so:

public void saveDoc(string doc, Word.Document wd)
{
    string path = @"\\servername\folder\subfolder\";
    object filename = path + doc + ".docx";
    try
    {
        wd.Activate();
        this.Application.ActiveDocument.SaveAs(ref filename);
    }
    catch (Exception e)
    {
        MessageBox.Show(e.Message);
    }
}

However this made no difference, the application's dialog still pops up, and regardless of whether I click OK or Cancel to the dialog it does not process the SaveAs command.

I have come to the conclusion that the application is intercepting the Save/SaveAs command and doing its own thing instead.

So is it possible to save a word document by bypassing the Save or SaveAs methods? Is there a way round this?

Figured it out, fortunately there was not a strict requirement to save it as a .doc or .docx so I have opted for .pdf . I have got round the application intercepting the Save commands by using the Document.ExportAsFixedFormat Method with wdExportFormatPDF to save it as a PDF.

So the final code looks like this, and it works a treat:

public void saveDoc(string doc)
    {
        string path = @"\\servername\folder\sub-folder\";
        string filename = path + doc + ".pdf";
        try
        {
            this.Application.ActiveDocument.ExportAsFixedFormat(filename, WdExportFormat.wdExportFormatPDF);
        }
        catch (Exception e)
        {
            MessageBox.Show(e.Message);
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM