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

标签 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。

最佳答案

有两个问题:

  • Word 互操作程序集通常无法写入磁盘以外的其他来源。这主要是因为 SDK 是一个基于 UI 的 SDK,它不是用来做后台的,因为它高度依赖于 UI。 (实际上,它只是对UI应用程序的包装,而不是其背后的逻辑层)

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

    Microsoft does not currently recommend, and does not support, Automation of Microsoft Office applications from any unattended, non-interactive client application or component (including ASP, ASP.NET, DCOM, and NT Services), because Office may exhibit unstable behavior and/or deadlock when Office is run in this environment.

所以这是不行的。

关于c# - 将Word文档转换为内存中的pdf字节数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34920847/

相关文章:

ios - 将 iPad 上的表单数据导出为可打印的 PDF

pdf - Autodesk PDF Extension - 防止查询字符串覆盖中的页面

javascript - 标题中的图像在 Word for Desktop 中显示,但在 Word Online 中消失

vba - 按标题(或标签)获取 ContentControl

c# - C#LINQ过滤

c# - SignalR 项目中的 Json 引用冲突

c# - 程序集版本控制不匹配? (.Net Core 2.0 与 .NET Standard 2 类库)

pdf - 将 pdf 正确转换为 ps,反之亦然

excel - 从 Excel 写入 Word Activex 文本框

java - 启动一个进程会启动另一个进程,该进程会启动 Java 进程吗?