Aspose.Words for .NET 下载地址 https://soft51.cc/software/175811283999782847
在实际应用中,除了文档内容本身,属性与元数据 也非常重要。它们用于描述文档的标题、作者、关键字、版本号,甚至安全性信息。Aspose.Words for .NET 提供了丰富的 API 来读取和修改这些信息。
Word 文档有一些 内置属性(Built-in Properties),如标题、作者、公司、关键字、创建时间等。
📌 示例:读取与修改内置属性
using Aspose.Words;
using Aspose.Words.Properties;
Document doc = new Document("input.docx");
// 读取内置属性
BuiltInDocumentProperties props = doc.BuiltInDocumentProperties;
Console.WriteLine("标题: " + props.Title);
Console.WriteLine("作者: " + props.Author);
Console.WriteLine("公司: " + props.Company);
// 修改属性
props.Title = "Aspose.Words 教程文档";
props.Author = "Han Bing";
props.Company = "My Company";
props.Keywords = "Aspose, Word, 教程";
// 保存
doc.Save("with-properties.docx");
除了内置属性,还可以创建 自定义属性(Custom Properties),用于存储个性化信息,例如版本号、项目编号等。
📌 示例:添加、读取、删除自定义属性
using Aspose.Words;
using Aspose.Words.Properties;
Document doc = new Document("input.docx");
// 添加自定义属性
CustomDocumentProperties customProps = doc.CustomDocumentProperties;
customProps.Add("ProjectID", "PRJ-2025-001");
customProps.Add("Reviewed", true);
customProps.Add("Version", 1.2);
// 读取自定义属性
foreach (DocumentProperty prop in customProps)
{
Console.WriteLine($"{prop.Name} = {prop.Value}");
}
// 删除自定义属性
if (customProps.Contains("Reviewed"))
customProps.Remove("Reviewed");
doc.Save("with-custom-properties.docx");
Aspose.Words 可以获取 统计信息(如字数、段落数、页数等),帮助快速分析文档规模。
📌 示例:获取统计信息
using Aspose.Words;
using Aspose.Words.Properties;
Document doc = new Document("input.docx");
BuiltInDocumentProperties props = doc.BuiltInDocumentProperties;
Console.WriteLine("页数: " + doc.PageCount);
Console.WriteLine("字数: " + props.Words);
Console.WriteLine("段落数: " + props.Paragraphs);
Console.WriteLine("字符数: " + props.Characters);
可以在文档属性或 自定义属性 中维护版本信息,便于文档管理。
📌 示例:维护版本号
using Aspose.Words;
using Aspose.Words.Properties;
Document doc = new Document("input.docx");
CustomDocumentProperties customProps = doc.CustomDocumentProperties;
// 如果已存在版本号,则更新
if (customProps.Contains("DocVersion"))
{
double version = (double)customProps["DocVersion"].Value;
customProps["DocVersion"].Value = version + 0.1;
}
else
{
customProps.Add("DocVersion", 1.0);
}
doc.Save("with-version.docx");
Aspose.Words 支持对文档进行 数字签名,保证文档的来源可信与内容完整性。同时还可以设置文档保护属性。
📌 示例:对文档添加数字签名
using Aspose.Words;
using Aspose.Words.DigitalSignatures;
using System;
Document doc = new Document("input.docx");
// 证书文件(.pfx),需要包含私钥
CertificateHolder cert = CertificateHolder.Create("mycert.pfx", "password");
// 数字签名详情
DigitalSignatureUtil.Sign("input.docx", "signed.docx", cert,
new SignOptions { Comments = "文档已签名", SignTime = DateTime.Now });
Console.WriteLine("文档签名完成。");
📌 示例:保护文档(只读 / 限制编辑)
using Aspose.Words;
Document doc = new Document("input.docx");
// 设置为只读保护
doc.Protect(ProtectionType.ReadOnly, "123456");
// 取消保护
// doc.Unprotect("123456");
doc.Save("protected.docx");
Aspose.Words for .NET 下载地址 https://soft51.cc/software/175811283999782847