题注是指对象下方(或上方)的一行简短文字,用于描述该对象。在Word中使用题注功能可以保证文档中图片、表格或图表等项目能够有序地自动编号。如果移动、插入或删除带题注的项目时,Word 可以自动更新。本文将详细介绍如何使用Spire.Doc来添加和删除题注。
添加题注
代码如下:
C#
//实例化Document对象
Document document = new Document();
//添加一个Section
Section s = document.AddSection();
//添加一个段落并在其中添加图片
Paragraph par1 = s.AddParagraph();
par1.Format.AfterSpacing = 10;
DocPicture pic1 = par1.AppendPicture(Image.FromFile(@"logo1.png"));
pic1.Height = 100;
pic1.Width = 120;
//在图片上添加题注
CaptionNumberingFormat format = CaptionNumberingFormat.Number;
pic1.AddCaption("Spire.Doc Logo_插 图", format, CaptionPosition.AfterImage);
//另加一个段落进行同样的操作
Paragraph par2 = s.AddParagraph();
DocPicture pic2 = par2.AppendPicture(Image.FromFile(@"logo2.png"));
pic2.Height = 100;
pic2.Width = 120;
pic2.AddCaption("Spire.Doc Logo_插 图", format, CaptionPosition.AfterImage);
//更新域并保存文档
document.IsUpdateFields = true;
document.SaveToFile("caption.docx", FileFormat.Docx);
VB.NET
'实例化Document对象
Dim document As Document = New Document
'添加一个Section
Dim s As Section = document.AddSection
'添加一个段落并在其中添加图片
Dim par1 As Paragraph = s.AddParagraph
par1.Format.AfterSpacing = 10
Dim pic1 As DocPicture = par1.AppendPicture(Image.FromFile("logo1.png"))
pic1.Height = 100
pic1.Width = 120
'在图片上添加题注
Dim format As CaptionNumberingFormat = CaptionNumberingFormat.Number
pic1.AddCaption("Spire.Doc Logo_插 图", format, CaptionPosition.AfterImage)
'另加一个段落进行同样的操作
Dim par2 As Paragraph = s.AddParagraph
Dim pic2 As DocPicture = par2.AppendPicture(Image.FromFile("logo2.png"))
pic2.Height = 100
pic2.Width = 120
pic2.AddCaption("Spire.Doc Logo_插 图", format, CaptionPosition.AfterImage)
'更新域并保存文档
document.IsUpdateFields = true
document.SaveToFile("caption.docx", FileFormat.Docx)
结果如图:
删除题注
代码如下:
C#
//加载刚才的结果文档
Document doc = new Document();
doc.LoadFromFile("caption.docx");
//查找然后获取第一个题注
TextSelection[] slcs = doc.FindAllString("Spire.Doc Logo_插 图", true, true);
TextRange tr=slcs[0].GetAsOneRange();
Paragraph para= tr.OwnerParagraph;
//删除其所在的段落
doc.Sections[0].Paragraphs.Remove(para);
//更新域, 发现第二张插图的序号现在更新为1了
doc.IsUpdateFields = true;
doc.SaveToFile("deleteCaption.docx",FileFormat.Docx2010);
VB.NET
'加载刚才的结果文档
Dim doc As Document = New Document
doc.LoadFromFile("caption.docx")
'查找然后获取第一个题注
Dim slcs() As TextSelection = doc.FindAllString("Spire.Doc Logo_插 图", true, true)
Dim tr As TextRange = slcs(0).GetAsOneRange
Dim para As Paragraph = tr.OwnerParagraph
'删除其所在的段落
doc.Sections(0).Paragraphs.Remove(para)
'更新域, 发现第二张插图的序号现在更新为1了
doc.IsUpdateFields = true
doc.SaveToFile("deleteCaption.docx", FileFormat.Docx2010)
结果如图: