Aspose.Words for .NET使用教程(九):將文檔轉(zhuǎn)換為字節(jié)數(shù)組和HTML
Aspose.Words無(wú)需Microsoft Word也可在任何平臺(tái)上滿足Word文檔的一切操作需求。本文將與大家分享如何將word和圖像轉(zhuǎn)換為PDF。
【下載Aspose.Words for .NET最新試用版】
將Document(文檔)轉(zhuǎn)換為Byte Array(字節(jié)數(shù)組)
本部分主要說(shuō)明如何序列化Document對(duì)象以獲取表示Document的字節(jié)數(shù)組,以及如何反序列化字節(jié)數(shù)組以再次獲取Document對(duì)象。在將文檔存儲(chǔ)在數(shù)據(jù)庫(kù)中或準(zhǔn)備文檔以在Web上傳輸時(shí),通常需要此技術(shù)。
用于序列化Document對(duì)象的最簡(jiǎn)單方法是首先使用Document類的Document.Save方法重載將其保存到MemoryStream。然后在流中調(diào)用ToArray方法,該方法返回以字節(jié)形式表示文檔的字節(jié)數(shù)組。選擇的保存格式非常重要,以確保在保存和重新加載到Document對(duì)象時(shí)保留最高保真度。 出于這個(gè)原因,建議使用OOXML格式。然后按照上述反向步驟以將字節(jié)加載回Document對(duì)象。你可以從下載此示例的模板文件。
// For complete examples and data files, please go to //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)信息將文檔轉(zhuǎn)換為HTML
當(dāng)文檔保存為HTML,MHTML或EPUB時(shí),Aspose.Words可以導(dǎo)出往返信息。HtmlSaveOptions.ExportRoundtripInformation屬性指定在保存為HTML,MHTML或EPUB時(shí)是否寫(xiě)入往返信息。 HTML的默認(rèn)值為true,MHTML和EPUB的默認(rèn)值為false。在HTML文檔加載回Document對(duì)象期間,保存往返信息允許恢復(fù)文章屬性,例如制表位,注釋,頁(yè)眉和頁(yè)腳。
如果為true,則將往返信息導(dǎo)出為 - aw - *相應(yīng)HTML元素的CSS屬性。
如果為false,則不會(huì)將往返信息輸出到生成的文件中。
下面的代碼示例顯示了在轉(zhuǎn)換Doc-> Html-> Doc時(shí)如何導(dǎo)出往返信息。你可以從下載此示例的模板文件。
// For complete examples and data files, please go to //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);