保存文档

您需要使用 Aspose.Words 执行的大多数任务都涉及保存文档。 Aspose.Words提供了Document类的Save方法来保存文档。有一些重载允许将文档保存到文件、流或 ASP.NET HttpResponse 对象以发送到客户端浏览器。文档可以保存为 Aspose.Words 支持的任何保存格式。有关所有支持的保存格式的列表,请参阅 SaveFormat 枚举。

保存到文件

只需使用带有文件名的 Save 方法即可。 Aspose.Words 将根据您指定的文件扩展名确定保存格式。

以下代码示例演示如何加载文档并将其保存到文件:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document doc = new Document(MyDir + "Document.doc");
doc.Save(ArtifactsDir + "BaseConversions.DocToDocx.docx");
view raw load-save.cs hosted with ❤ by GitHub

保存到流

将流对象传递给 Save 方法。保存到流时需要明确指定保存格式。

以下代码示例演示如何将文档加载和保存到流中:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// Read only access is enough for Aspose.Words to load a document.
Stream stream = File.OpenRead(MyDir + "Document.docx");
Document doc = new Document(stream);
// You can close the stream now, it is no longer needed because the document is in memory.
stream.Close();
// ... do something with the document.
// Convert the document to a different format and save to stream.
MemoryStream dstStream = new MemoryStream();
doc.Save(dstStream, SaveFormat.Rtf);
// Rewind the stream position back to zero so it is ready for the next reader.
dstStream.Position = 0;

将文档发送到客户端浏览器

为了将文档发送到客户端浏览器,请使用带有四个参数的特殊重载:文件名、保存格式、保存类型和 ASP.NET HttpResponse 对象。文档呈现给用户的方式由 ContentDisposition 枚举表示,它确定发送到浏览器的文档是否提供直接在浏览器中或在与文件扩展名关联的应用程序中打开自身的选项。

以下代码示例演示如何从 ASP.NET 代码将文档发送到客户端浏览器:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document doc = new Document(MyDir + "Document.docx");
// If this method overload is causing a compiler error then you are using the Client Profile DLL whereas
// the Aspose.Words .NET 2.0 DLL must be used instead.
doc.Save(ArtifactsDir + "BaseConversions.DocxToDocx.docx");

使用 .NET 客户端配置文件 DLL 时,Save 方法的此重载不可用。该 DLL 位于 net3.5_ClientProfile 文件夹中。 .NET 客户端配置文件不包括 System.Web 等程序集,因此 HttpResponse 不可用。这完全是设计使然。

这可能会表现为错误:

"‘Save’方法没有重载,需要‘4’个参数。"

如果您需要在 ASP.NET 应用程序中使用 Aspose.Words,建议使用可提供正确重载的 .NET 2.0 DLL,如本文所述。

保存到 PCL

Aspose.Words 支持将文档保存为 PCL(打印机命令语言)。 Aspose.Words 可以将文档保存为 PCL 6(PCL 6 增强型或 PCL XL)格式。 PclSaveOptions 类可用于在将文档保存为 PCL 格式时指定附加选项。

以下代码示例演示如何使用保存选项将文档保存到 PCL:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document doc = new Document(MyDir + "Rendering.docx");
PclSaveOptions saveOptions = new PclSaveOptions { SaveFormat = SaveFormat.Pcl };
doc.Save(ArtifactsDir + "BaseConversions.DocxToPcl.pcl", saveOptions);
view raw docx-to-pcl.cs hosted with ❤ by GitHub

也可以看看