Microsoft.Office.Interop是否可安全地用于网站的(文件转换)?

问题描述:

我正在编写一个女巫用户必须添加报告(Word文档)的网站,并使其可以查看它们,我将* .doc转换为* .pdf,然后通过pdf.js显示它们。对于转换我使用Microsoft.Office.Interop.Word。代码如下所示Microsoft.Office.Interop是否可安全地用于网站的(文件转换)?

public void ConvertDocument(string PATH) 
    { 
     FileInfo FILE = new FileInfo(PATH); 

     if (FILE.Extension.ToLower() == ".doc" || FILE.Extension.ToLower() == ".docx" || FILE.Extension.ToLower() == ".docm" || FILE.Extension.ToLower() == ".dotx" || FILE.Extension.ToLower() == ".dotm") 
     { 
      if (FILE.Length == 0) 
      { 
       return; 
      } 

      object oMissing = System.Reflection.Missing.Value; 
      Word.Application word = new Word.Application(); 

      try 
      { 
       word.Visible = false; 
       word.ScreenUpdating = false; 

       Object filename = (Object)FILE.FullName; 
       Word.Document doc = word.Documents.Open(ref filename, 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, ref oMissing); 
       try 
       { 
        doc.Activate(); 
        object outputFileName = FILE.FullName.Replace(FILE.Extension, ".PDF"); 
        doc.SaveAs(ref outputFileName, Word.WdSaveFormat.wdFormatPDF, 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); 
       } 

       finally 
       { 
        object saveChanges = Word.WdSaveOptions.wdDoNotSaveChanges; 
        ((Word._Document)doc).Close(ref saveChanges, ref oMissing, ref oMissing); 
        doc = null; 
       } 
      } 

      finally 
      { 
       ((Word._Application)word).Quit(ref oMissing, ref oMissing, ref oMissing); 
       word = null; 
      } 

      File.Delete(PATH); 
     } 
} 
  1. 那是安全的吗?
  2. 它会处理多少用户?
  3. 它需要什么资源?
  4. 我应该在服务器上安装MS Office来运行网站吗?
  5. 这实际上是一种很好的方法吗?

答案,从微软,是否定的:

微软目前并不提倡,不支持, 自动化的Microsoft Office应用程序从任何无人值守, 非交互式客户端应用程序或组件(包括ASP, ASP.NET,DCOM和NT服务),因为Office在此环境中运行时可能会出现不稳定的 行为和/或死锁。

Considerations for Server-Side Automation of Office

从经验来看,这里是我们遇到的问题:

  • 当进程意外存在,大量的Word实例都留给左右,而从不清理
  • 通过处理会话中途关闭发生后,Word安装已损坏
  • 它不能很好地扩展 - Word是一个很大的d esktop应用程序的功能非常出色;然而,它并不是真的用于你正在使用它的过程,因此,打开它的很多实例会占用应用程序可以使用的资源。

,还有其他的方法可以做到这一点,但是作为覆盖this StackOverflow question and answers

您可以考虑预转换的Word文档 - 例如,是否有可能,文件上传时,还创建那么PDF呢?这样,你的服务器只是提供一个PDF文档,并且在服务请求时不得不做很少的工作。