脚注通常位于Word文档页面底端,用于对文档中某个内容提供解释、说明或相关的参考资料。如果同一脚注在文档的两处被引用,应该只在前一个引用的地方插入脚注,在第二次被引用的地方采用“交叉引用”。本文将介绍如何使用Free Spire.Doc组件和C#在Word中插入脚注以及设置交叉引用。
在使用以下代码前,需要先在Visual studio中创建一个C#应用程序,并引用Spire.Doc.dll到工程中。
需要用到的命名空间:
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
主要代码:
//加载文档
Document document = new Document();
document.LoadFromFile(@"Input.docx");
//查找需要添加脚注的文本及其所在的段落
TextSelection ts = document.FindString("椭圆定律", true, true);
TextRange textrRange = ts.GetAsOneRange();
Paragraph paragraph = textrRange.OwnerParagraph;
//创建脚注
Footnote footnote = new Footnote(document);
footnote.FootnoteType = FootnoteType.Footnote;
//添加脚注的注释文本,并设置它的注释引用标记格式为上标(脚注由注释引用标记及其对应的注释文本组成)
Paragraph footPar = footnote.TextBody.AddParagraph();
footPar.AppendText("是德国天文学家开普勒提出的关于行星运动的三大定律之一");
footnote.MarkerCharacterFormat.SubSuperScript = SubSuperScript.SuperScript;
//将脚注插入到文本之后
paragraph.ChildObjects.Insert(paragraph.ChildObjects.IndexOf(textrRange) + 1, footnote);
//第二步:创建交叉引用域并链接到脚注
//添加书签"_FootNote1"到脚注注释文本所在位置
BookmarkStart start = new BookmarkStart(document, "_FootNote1");
BookmarkEnd end = new BookmarkEnd(document, "_FootNote1");
footPar.ChildObjects.Insert(0, start);
footPar.ChildObjects.Insert(footPar.ChildObjects.Count - 1, end);
//创建交叉引用域,并通过书签将其链接到脚注注释文本
Field field = new Field(document);
field.Type = FieldType.FieldNoteRef;
field.Code = @" NOTEREF _FootNote1 \f \h \* MERGEFORMAT ";
//查找需要引用相同脚注的文本及其所在的段落
textrRange = document.FindString("轨道定律", true, false).GetAsOneRange();
paragraph = textrRange.OwnerParagraph;
//插入交叉引用域到文本之后
paragraph.ChildObjects.Insert(paragraph.ChildObjects.IndexOf(textrRange) + 1, field);
//添加分隔符(分隔符是用来分割域代码和域结果的,该步骤不可以省略)
FieldMark fieldmark = new FieldMark(document, FieldMarkType.FieldSeparator);
paragraph.ChildObjects.Insert(paragraph.ChildObjects.IndexOf(textrRange) + 2, fieldmark);
//添加上标到文本之后
TextRange tr = new TextRange(document);
tr.Text = "1";
tr.CharacterFormat.SubSuperScript = SubSuperScript.SuperScript;
paragraph.ChildObjects.Insert(paragraph.ChildObjects.IndexOf(textrRange) + 3, tr);
//添加域结束标记(该步骤不可以省略)
FieldMark fieldEnd = new FieldMark(document, FieldMarkType.FieldEnd);
paragraph.ChildObjects.Add(fieldEnd);
//保存文档
document.SaveToFile("脚注.docx", FileFormat.Docx);
如果觉得脚注注释文本和正文的内容不匹配,可以通过以下代码设置其字体格式和颜色:
TextRange text = footPar.AppendText("是德国天文学家开普勒提出的关于行星运动的三大定律之一");
text.CharacterFormat.FontName = "Arial Black";
text.CharacterFormat.FontSize = 10;
text.CharacterFormat.TextColor = Color.DarkGray;
效果图: