我需要打開一個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格式。
作爲對您評論的回覆,您可以嘗試[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)是查找和替換示例代碼。 –