将Word文档转换为内存中的pdf字节数组

时间:2016-01-21 10:13:55

标签: c# pdf ms-word

我需要打开一个Microsoft Word文档,替换一些文本然后转换为pdf字节数组。我已经创建了代码来执行此操作,但它涉及将pdf保存到磁盘并将字节读回内存。我想避免在磁盘上写任何东西,因为我不需要保存文件。

以下是我到目前为止所做的代码......

using System.IO;
using Microsoft.Office.Interop.Word;

public byte[] ConvertWordToPdfArray(string fileName, string newText)
{
    // Temporary path to save pdf
    string pdfName = fileName.Substring(0, fileName.Length - 4) + ".pdf";

    // Create a new Microsoft Word application object and open the document
    Application app = new Application();
    Document doc = app.Documents.Open(docName);

    // Make any necessary changes to the document
    Selection selection = doc.ActiveWindow.Selection;
    selection.Find.Text = "{{newText}}";
    selection.Find.Forward = true;
    selection.Find.MatchWholeWord = false;
    selection.Find.Replacement.Text = newText;
    selection.Find.Execute(Replace: WdReplace.wdReplaceAll);

    // Save the pdf to disk
    doc.ExportAsFixedFormat(pdfName, WdExportFormat.wdExportFormatPDF);

    // Close the document and exit Word
    doc.Close(false);
    app.Quit();
    app = null;

    // Read the pdf into an array of bytes
    byte[] bytes = File.ReadAllBytes(pdfName);

    // Delete the pdf from the disk
    File.Delete(pdfName);

    // Return the array of bytes
    return bytes;
}

如果不写入磁盘,如何才能获得相同的结果?整个操作需要在内存中运行。

为了解释我为什么需要这样做,我希望ASP.NET MVC应用程序的用户能够将报表模板上传为word文档,该文档在返回到浏览器时呈现为pdf。

1 个答案:

答案 0 :(得分:4)

有两个问题:

  • Word互操作程序集通常无法写入除磁盘之外的其他源。这主要是因为SDK是基于UI的SDK,它并不意味着做背景,因为它高度依赖于UI。 (事实上​​,它只是UI应用程序的包装器,而不是它背后的逻辑层)

  • 您不应在ASP.NET上使用Office互操作程序集。阅读Considerations for server-side Automation of Office,其中说明:

      

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

所以这是不行的。

相关问题