Aspose.Words for .NET 下载地址 https://soft51.cc/software/175811283999782847
在 Aspose.Words for .NET 中,创建和加载文档是最基础的操作。本章将介绍 六种常见场景:从零创建文档、从文件加载、从流加载、从字符串创建、处理受保护文档,以及文档加载选项的配置。
创建新文档有两种常见方法:
📌 示例:创建空白文档并写入内容
using Aspose.Words;
Document doc = new Document(); // 创建一个空白文档
DocumentBuilder builder = new DocumentBuilder(doc);
builder.Writeln("Hello, Aspose.Words!"); // 插入一段文字
builder.Writeln("这是第二段。");
// 保存
doc.Save("NewDocument.docx");
Aspose.Words 支持多种主流格式,如 DOC、DOCX、RTF、ODT、HTML、TXT 等。
📌 示例:从不同格式加载
Document doc1 = new Document("input.docx");
Document doc2 = new Document("input.rtf");
Document doc3 = new Document("input.html");
如果文档存储在数据库或 Web API 返回的字节流中,可以使用 Stream
直接加载。
📌 示例:从内存流加载文档
using System.IO;
using Aspose.Words;
byte[] fileBytes = File.ReadAllBytes("input.docx");
using (MemoryStream ms = new MemoryStream(fileBytes))
{
Document doc = new Document(ms);
Console.WriteLine("文档页数: " + doc.PageCount);
}
可以通过 HTML 或纯文本字符串快速生成文档。
📌 示例:从 HTML 字符串创建
string html = "<html><body><h1>标题</h1><p>这是一个段落。</p></body></html>";
Document doc = new Document(new MemoryStream(System.Text.Encoding.UTF8.GetBytes(html)));
doc.Save("FromString.docx");
Aspose.Words 支持加载 带密码的文档,需要传入 LoadOptions
设置密码。
📌 示例:打开受保护文档
using Aspose.Words;
LoadOptions options = new LoadOptions("password123"); // 设置打开密码
Document doc = new Document("Protected.docx", options);
Console.WriteLine("成功加载受保护文档,页数: " + doc.PageCount);
LoadOptions
提供了丰富的加载配置,比如:
Password
→ 打开加密文档LoadFormat
→ 指定文档格式Encoding
→ 处理 TXT/HTML 编码ConvertMetafilesToPng
→ 控制图元文件转换📌 示例:配置加载选项
using Aspose.Words;
using System.Text;
LoadOptions options = new LoadOptions
{
Encoding = Encoding.UTF8, // 指定编码
LoadFormat = LoadFormat.Html, // 明确指定格式
Password = null // 不设置密码
};
Document doc = new Document("input.html", options);
doc.Save("Loaded.docx");
Document
+ DocumentBuilder
。LoadOptions
设置密码。Aspose.Words for .NET 下载地址 https://soft51.cc/software/175811283999782847