2016-01-21 115 views
4

我需要打開一個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格式。

+1

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

回答

4

有兩個問題:

  • 話語互操作程序集通常不能寫入到另一個來源比磁盤。這主要是因爲SDK是一個基於UI的SDK,由於它高度依賴於用戶界面,因此不打算做後臺工作。 (實際上,它僅僅是圍繞UI應用程序的封裝,而不是其背後的邏輯層)

  • 不應該在ASP.NET上使用Office互操作程序集。閱讀Considerations for server-side Automation of Office,其中規定:

    微軟目前並不提倡,不支持,Microsoft Office應用程序自動化從任何無人蔘與的非交互式客戶端應用程序或組件(包括ASP,ASP.NET,DCOM,和NT服務),因爲Office在此環境中運行時可能會出現不穩定的行爲和/或死鎖。

因此,這是一個沒有去。

+0

這使得清楚如何編輯Word文檔感謝,但我仍然需要知道如何轉換爲PDF。是否有任何程序集可以進行轉換並返回一個不昂貴的字節數組? – Anthony