【发布时间】: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.Document。 Here 是将文档转换为 PDF 的代码,here 是将文档下载到 ASP.NET MVC 客户端浏览器的代码(无需先将其保存到物理文件),here 是查找和替换示例代码。