首页 > 解决方案 > 使用 Interop 将 Word 文档保存为 pdf 会导致 COMException:命令失败

问题描述

我有一个 ASP.NET MVC 应用程序,该应用程序池配置为作为自定义身份帐户运行,例如 MyDomain\MyUser。

从 word docx 文件创建 pdf 文件时遇到问题:尝试将文件另存为 pdf 到应用程序文件夹中的临时文件夹时出现“COMException 命令失败”:C:\inetpub\wwwroot\MyAspNetMvcApp\Data\Documents \温度

我已将应用程序池自定义身份帐户 (MyDomain\MyUser) 添加到具有完全控制权限的应用程序文件夹中,但它不起作用,无法将 pdf 保存到应用程序文件夹中。

我已经使用服务器上的进程监视器对其进行了调试,以处理来自应用程序文件夹的传入文件系统事件,并且我可以看到,当使用 Interop 提供的 SaveAs2 方法时,服务器上的 WINWORD.EXE 被调用/执行,但使用的是域用户帐户登录客户端计算机而不是使用应用程序池自定义身份帐户 (MyDomain\MyUser),因此当尝试将新的 pdf 文件写入 C:\inetpub\wwwroot\MyAspNetMvcApp\Data\Documents\Temp 时出现异常“COMException 命令failed" 被抛出,因为它无权在那里写入。

我已将身份设置为 Microsoft Word DCOM 组件的“交互式用户”。

由于应用程序池自定义身份帐户有权写入该应用程序文件夹,我如何使用应用程序池自定义身份帐户强制执行 Interop SaveAs2 方法?

代码片段下方:

public void ConvertToPDF(string myDocFile)
{
    // myDocFile contains "C:\\inetpub\\wwwroot\\MyAspNetMvcApp\\Data\\Documents\\Temp\\myDocxFile.docx"
    Document myDoc = GetMyDoc(myDocFile);

    string myPdfFile = Path.Combine(Path.GetDirectoryName(myDocFile), Path.GetFileNameWithoutExtension(myDocFile) + ".pdf");

    // myPdfFile now contains: "C:\\inetpub\\wwwroot\\MyAspNetMvcApp\\Data\\Documents\\Temp\\myPdfFile.pdf"

    // How can I force below SaveAs2 method to execute using the application pool custom account (the same account which runs w3wp.exe)?
    myDoc.SaveAs2(myPdfFile, WdSaveFormat.wdFormatPDF); // <--- HERE IT CRASHES: COMException command failed!!
    
    ...
}

public Document GetMyDoc(object docfile)
{
   // docFile contains "C:\\inetpub\\wwwroot\\MyAspNetMvcApp\\Data\\Documents\\Temp\\myDocxFile.docx"

   Application wApp = new Microsoft.Office.Interop.Word.Application();
   Document myDoc = wApp.Documents.Open(ref docFile);
   
   return myDoc;
}

标签: asp.net-mvciisoffice-interopw3wpword-interop

解决方案


推荐阅读