在本主题中,我们将解释如何使用 C# 在 Word 文档中插入注释。 MS Word 中的注释注释锚定到文本中的某个位置或文本区域。 在 Aspose.Words 的文档对象模型中,注释是一个内联节点,并且只能是段落的子节点。 我们将使用示例输入 Word 文档并在 DOCX 的开头插入一条注释,其中包含几行 C# 代码。 您可以使用相同的方法将注释插入文档中的任何段落。
使用 C# 在 Word 文档中插入注释的步骤
- 从 NuGet.org 安装 Aspose.Words for .NET 包
- 添加对 Aspose.Words 的引用
- 在导入文档之前使用 License.SetLicense 方法设置许可证
- 导入输入的Word文档
- 初始化 DocumentBuilder 类的实例并将光标移动到文档的开头
- 初始化 Comment 类的实例并使用 Paragraph 添加评论文本
- 在文档的第一段添加评论
- 最后,将文档保存为 Word DOCX 文件格式
之前,我们研究了 如何在没有互操作的 C# 中将 PDF 转换为 Word。 现在,您将学习如何将评论插入 DOCX 文件格式。
使用 C# 在 Word 文档中插入注释的代码
using Aspose.Words; | |
using System; | |
namespace InsertCommentinWord | |
{ | |
class how_to_insert_comment_into_word_document_using_c_sharp | |
{ | |
public static void InsertComment(String directorypath) | |
{ | |
//Set Aspose license before importing document. | |
Aspose.Words.License AsposeWordsLicense = new Aspose.Words.License(); | |
AsposeWordsLicense.SetLicense(directorypath + @"Aspose.Words.lic"); | |
//Import the Document into Aspose.Words DOM. | |
Document doc = new Document(directorypath + "input.docx"); | |
DocumentBuilder builder = new DocumentBuilder(doc); | |
//Move the cursor to the beginning of the document. | |
builder.MoveToDocumentStart(); | |
//Insert comment to first paragraph of document. | |
Comment comment = new Comment(doc, "Aspose.Words", "AW", DateTime.Today); | |
builder.CurrentParagraph.AppendChild(comment); | |
comment.Paragraphs.Add(new Paragraph(doc)); | |
comment.FirstParagraph.Runs.Add(new Run(doc, "Comment text.")); | |
//Save the Document | |
doc.Save(directorypath + @"output.docx", SaveFormat.Docx); | |
} | |
} | |
} |
使用上面的 C# 代码在 Word 文档中插入注释不需要安装 MS Office,可以在安装了 .NET 的地方使用。 此代码示例在文档第一段的末尾插入注释。