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最新资源合集

猜你喜欢

转载自blog.csdn.net/weixin_43746001/article/details/88056351