【问题标题】:Convert Word document to pdf byte array in memory将Word文档转换为内存中的pdf字节数组
【发布时间】:2016-04-27 12:38:48
【问题描述】:

我需要打开一个 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。

【问题讨论】:

  • 作为对您评论的回复,您可以尝试GemBox.DocumentHere 是将文档转换为 PDF 的代码,here 是将文档下载到 ASP.NET MVC 客户端浏览器的代码(无需先将其保存到物理文件),here 是查找和替换示例代码。

标签: c# pdf ms-word


【解决方案1】:

有两个问题:

  • 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 在此环境中运行时出现的行为和/或死锁。

所以这是不行的。

【讨论】:

  • 这清楚地说明了如何编辑 Word 文档,谢谢,但我仍然需要知道如何转换为 PDF。是否有任何程序集可以进行转换并返回不昂贵的字节数组?
猜你喜欢
  • 2015-03-12
  • 1970-01-01
  • 1970-01-01
  • 2012-11-09
  • 2012-08-07
  • 1970-01-01
  • 1970-01-01
  • 2015-09-16
  • 2011-11-10
相关资源
最近更新 更多