Aspose.Words for .NET使用教程(九):將文檔轉換爲字節數組和HTML

Aspose.Words無需Microsoft Word也可在任何平臺上滿足Word文檔的一切操作需求。本文將與大家分享如何將word和圖像轉換爲PDF


將Document(文檔)轉換爲Byte Array(字節數組)


本部分主要說明如何序列化Document對象以獲取表示Document的字節數組,以及如何反序列化字節數組以再次獲取Document對象。在將文檔存儲在數據庫中或準備文檔以在Web上傳輸時,通常需要此技術。

用於序列化Document對象的最簡單方法是首先使用Document類的Document.Save方法重載將其保存到MemoryStream。然後在流中調用ToArray方法,該方法返回以字節形式表示文檔的字節數組。選擇的保存格式非常重要,以確保在保存和重新加載到Document對象時保留最高保真度。 出於這個原因,建議使用OOXML格式。然後按照上述反向步驟以將字節加載回Document對象。你可以從此處下載此示例的模板文件。

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_LoadingAndSaving();

// Load the document from disk.
Document doc = new Document(dataDir + "Test File (doc).doc");

// Create a new memory stream.
MemoryStream outStream = new MemoryStream();
// Save the document to stream.
doc.Save(outStream, SaveFormat.Docx);

// Convert the document to byte form.
byte[] docBytes = outStream.ToArray();

// The bytes are now ready to be stored/transmitted.

// Now reverse the steps to load the bytes back into a document object.
MemoryStream inStream = new MemoryStream(docBytes);

// Load the stream into a new document object.
Document loadDoc = new Document(inStream);


使用往返(Roundtrip)信息將文檔轉換爲HTML


當文檔保存爲HTML,MHTML或EPUB時,Aspose.Words可以導出往返信息。HtmlSaveOptions.ExportRoundtripInformation屬性指定在保存爲HTML,MHTML或EPUB時是否寫入往返信息。 HTML的默認值爲true,MHTML和EPUB的默認值爲false。在HTML文檔加載回Document對象期間,保存往返信息允許恢復文章屬性,例如製表位,註釋,頁眉和頁腳。

如果爲true,則將往返信息導出爲 - aw - *相應HTML元素的CSS屬性。

如果爲false,則不會將往返信息輸出到生成的文件中。

下面的代碼示例顯示了在轉換Doc-> Html-> Doc時如何導出往返信息。你可以從此處下載此示例的模板文件。

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_LoadingAndSaving();

// Load the document from disk.
Document doc = new Document(dataDir + "Test File (doc).doc");

HtmlSaveOptions options = new HtmlSaveOptions();

// HtmlSaveOptions.ExportRoundtripInformation property specifies
// Whether to write the roundtrip information when saving to HTML, MHTML or EPUB.
// Default value is true for HTML and false for MHTML and EPUB.
options.ExportRoundtripInformation = true;
            
doc.Save(dataDir + "ExportRoundtripInformation_out.html", options);

下載Aspose.Words for .NET最新試用版

爲你推薦:Aspose專題 - Aspose最新資源合集


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章