Microsoft.Office.Interop.Word错误:-2146824090(COM异常,命令失败)

时间:2014-12-12 16:06:23

标签: c# com office-interop comexception

我有一种方法可用于将Word文件另存为PDF,以便打印批量文档pdf,doc和docx。当只有一个word文档(doc或docx)且只打印一个批处理时,它会按预期执行。但是,如果有多个word文档,或者它必须为多个批次打印相同的word文档,则会在SaveAs方法调用时失败。

该方法定义如下:

    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:该方法循环遍历文档列表中的所有文件,并且仅针对word文档调用。随后的PDF将添加到一个较大的PDF文件中,然后使用Adobe的打印功能进行打印。

0 个答案:

没有答案