我编写了一个将Word文档转换为PDF的函数。该代码非常适用于将doc和docx文件转换为PDF。但是对于某些单词文档,应用程序会抛出异常"命令失败"。
对于产生此错误的其中一个文件,我尝试通过导航到文件>来修改文件的现有设置。帮助>选项>信托中心>信任中心设置>文件阻止设置,但它没有工作。
我使用以下代码进行转换:
Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.Application();
//Opening the Word document that is temporarily created
Microsoft.Office.Interop.Word.Document doc = app.Documents.Open(tempPath);
// VERY IMPORTANT: do this to close the MS Word instance
doc.SaveAs(pdfFilePath, WdSaveFormat.wdFormatPDF);
((Microsoft.Office.Interop.Word._Document)doc).Close();
((Microsoft.Office.Interop.Word._Application)app).Quit();
//Additional code to close Word Document and release resources after opening
if (app != null)
System.Runtime.InteropServices.Marshal.ReleaseComObject(app);
if (doc != null)
System.Runtime.InteropServices.Marshal.ReleaseComObject(doc);
" TEMPPATH"是word文档的位置和" pdfFilepath"是保存pdf文档的位置。