Aspose.Words for .NET 教程(三):文档创建与加载全解析

作者:微信公众号:【架构师老卢】
9-22 16:29
8

Aspose.Words for .NET 下载地址 https://soft51.cc/software/175811283999782847


第三章 文档创建与加载详解

在 Aspose.Words for .NET 中,创建和加载文档是最基础的操作。本章将介绍 六种常见场景:从零创建文档、从文件加载、从流加载、从字符串创建、处理受保护文档,以及文档加载选项的配置。


3.1 创建新文档的多种方式

创建新文档有两种常见方法:

  1. 空白文档(默认包含一个空的 Section 和 Body)
  2. 使用 DocumentBuilder 插入内容

📌 示例:创建空白文档并写入内容

using Aspose.Words;

Document doc = new Document();              // 创建一个空白文档
DocumentBuilder builder = new DocumentBuilder(doc);

builder.Writeln("Hello, Aspose.Words!");    // 插入一段文字
builder.Writeln("这是第二段。");

// 保存
doc.Save("NewDocument.docx");

3.2 从文件加载文档(DOC/DOCX/RTF 等格式)

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");

3.3 从流加载文档

如果文档存储在数据库或 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);
}

3.4 从字符串创建文档

可以通过 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");

3.5 处理受保护的文档

Aspose.Words 支持加载 带密码的文档,需要传入 LoadOptions 设置密码。

📌 示例:打开受保护文档

using Aspose.Words;

LoadOptions options = new LoadOptions("password123"); // 设置打开密码
Document doc = new Document("Protected.docx", options);
Console.WriteLine("成功加载受保护文档,页数: " + doc.PageCount);

3.6 文档加载选项配置

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
  • 文件加载 → 支持 DOC/DOCX/RTF/HTML/TXT 等格式。
  • 流加载 → 适合数据库和网络传输场景。
  • 字符串创建 → 快速从 HTML/文本生成文档。
  • 受保护文档 → 使用 LoadOptions 设置密码。
  • 加载选项 → 提供格式、编码、图像等灵活控制。

Aspose.Words for .NET 下载地址 https://soft51.cc/software/175811283999782847

相关留言评论
昵称:
邮箱:
阅读排行