Microsoft.Office.Interop.Word Error : -2146824090 (COM Exception, Command Failed)

2.4k Views Asked by At

I have a method that I'm using to save a Word file as a PDF, for the purposes of printing batches of documents pdf, doc and docx alike. When there is only one word document (doc or docx) and only one batch is printing, it performs as expected. However, if there are multiple word documents, or it has to print the same word document for multiple batches, it fails at the SaveAs method call.

The method is defined below :

    private string ConvertWordToPDF(string wordFilename)
    {
        string outputfileName = Path.GetFileName(wordFilename);

        var myDocumentsFolderPath = Environment.GetFolderPath(Environment.SpecialFolder.CommonDocuments);
        var outputPath = myDocumentsFolderPath + "\\" + outputfileName;

        outputPath = outputPath.Replace(outputPath.ToLower().Contains(".docx") ? ".docx" : ".doc", ".pdf");

        if (System.IO.File.Exists(outputPath))
        {
            System.IO.File.Delete(outputPath);
        }

        if (Process.GetProcessesByName("winword").Any())
        {
            foreach (var proc in Process.GetProcessesByName("winword"))
            {
                proc.Kill();
                proc.WaitForExit();
            }
        }

        object oMissing = System.Reflection.Missing.Value;
        var appWord = new Word.Application();
        appWord.Visible = false;
        appWord.DisplayAlerts = WdAlertLevel.wdAlertsNone;
        appWord.Options.SavePropertiesPrompt = false;
        appWord.Options.SaveNormalPrompt = false;

        var wordDocument = appWord.Documents.Open(wordFilename);

        wordDocument.Activate();
        wordDocument.SaveAs(outputPath, WdExportFormat.wdExportFormatPDF,
            ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
            ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
            ref oMissing, ref oMissing);
        object saveChanges = WdSaveOptions.wdDoNotSaveChanges;
        wordDocument.Close(saveChanges);
        appWord.Quit(false);
        return outputPath;
    }

For Context: The method is in a loop over all files in a list of documents, and is only called for word documents. The subsequent PDF is added to one larger PDF file, and then printed using Adobe's print functionality.

0

There are 0 best solutions below