在内存中将Word文档转换为pdf字节数组
我需要打开一个Microsoft Word文档,替换一些文本然后转换为pdf字节数组。我已经创建了代码来执行此操作,但它涉及将pdf保存到磁盘并将字节读回到内存中。我想避免写任何东西到磁盘上,因为我不需要保存文件。在内存中将Word文档转换为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格式。
有两个问题:
话语互操作程序集通常不能写入到另一个来源比磁盘。这主要是因为SDK是一个基于UI的SDK,由于它高度依赖于用户界面,因此不打算做后台工作。 (实际上,它仅仅是围绕UI应用程序的封装,而不是其背后的逻辑层)
-
不应该在ASP.NET上使用Office互操作程序集。阅读Considerations for server-side Automation of Office,其中规定:
微软目前并不提倡,不支持,Microsoft Office应用程序自动化从任何无人参与的非交互式客户端应用程序或组件(包括ASP,ASP.NET,DCOM,和NT服务),因为Office在此环境中运行时可能会出现不稳定的行为和/或死锁。
因此,这是一个没有去。
这使得清楚如何编辑Word文档感谢,但我仍然需要知道如何转换为PDF。是否有任何程序集可以进行转换并返回一个不昂贵的字节数组? – Anthony
作为对您评论的回复,您可以尝试[GemBox.Document](http://www.gemboxsoftware.com/document/overview)。 [Here](http://www.gemboxsoftware.com/document/articles/c-sharp-vb-net-convert-word-to-pdf)是用于将您的文档转换为PDF的代码,[here](http: //www.gemboxsoftware.com/support-center/kb/articles/30-working-with-document-file-stream)是用于将文档下载到ASP.NET MVC客户端浏览器的代码(无需先将其保存到物理文件中)和[这里](http://www.gemboxsoftware.com/SampleExplorer/Document/ContentManipulation/FindandReplace)是查找和替换示例代码。 –