Word .NET库组件Spire.Doc系列教程(33): 在Word中添加和删除页眉页脚
Spire.Doc for .NET是一个专业的Word .NET库,设计用于帮助开发人员高效地开发创建、阅读、编写、转换和打印任何来自.NET( C#, VB.NET, ASP.NET)平台的Word文档文件的功能。
本系列教程将为大家带来Spire.Doc for .NET在使用过程中的各类实际操作,在Word工具栏里,我们通常会设置页眉,页脚,页码来对word文档进行排版。本文将详细介绍如何使用C#为word文档添加页眉,页脚和页码。>>下载Spire.Doc最新试用版体验
为 Word 文档添加页眉,页脚和页码
如果Word文档包含许多页,我们可以在页眉页脚处添加页码。该页码可显示当前页数, 总页数。我们以在页脚处添加页码为例:
Document document = new Document();
Section sec = document.AddSection();
Paragraph para = sec.AddParagraph();
para.AppendText("Page 1");
para.AppendBreak(BreakType.PageBreak);
para.AppendText("Page 2");
HeaderFooter footer = sec.HeadersFooters.Footer;
Paragraph footerPara = footer.AddParagraph();
footerPara.AppendField("页码", FieldType.FieldPage);
footerPara.AppendText(" of ");
footerPara.AppendField("总页数", FieldType.FieldNumPages);
footerPara.Format.HorizontalAlignment = HorizontalAlignment.Right;
document.SaveToFile("添加页码.docx", FileFormat.Docx);
图片和文字都能被添加为页眉或页脚,我们用C#来为word文档添加图文混排的页眉为例。
Document document = new Document();
Section sec = document.AddSection();
Paragraph para = sec.AddParagraph();
para.AppendText("Page 1");
HeaderFooter header = sec.HeadersFooters.Header;
Paragraph headerPara = header.AddParagraph();
//Add text and image to the header
DocPicture headerImage = headerPara.AppendPicture(Image.FromFile("logo.jpg"));
TextRange TR = headerPara.AppendText("成都冰蓝科技");
document.SaveToFile("图文页眉.docx", FileFormat.Docx);
同时,我们可以通过 TextWrappingStyle 和 TextWrappingType来设置图片在文本中的位置和自动换行:
headerImage.TextWrappingStyle = TextWrappingStyle.Through; headerImage.TextWrappingType = TextWrappingType.Left;
在C#里实现Word页眉页脚的奇偶页不同和星空最火知名网站不同。主要代码设置如下所示,具体的页眉和页脚步骤参照上述。
sec.PageSetup.DifferentOddAndEvenPagesHeaderFooter = true; sec.PageSetup.DifferentFirstPageHeaderFooter = true;
删除word文档中的页眉页脚
彻底删除word文档中的页眉页脚,运行后,word文档中所有页面的页眉页脚全部被清除。
//创建一个Document实例并加载示例文档
Document doc = new Document();
doc.LoadFromFile("Sample.docx");
//获取第一个section
Section section = doc.Sections[0];
//删除页眉
section.HeadersFooters.Header.ChildObjects.Clear();
//删除页脚
section.HeadersFooters.Footer.ChildObjects.Clear();
//保存文档
doc.SaveToFile("ClearHeaderFooter.docx", FileFormat.Docx);
仅删除word文档第一页的页眉页脚,其余页面保留页眉页脚。
//创建一个Document实例并加载示例文档
Document doc = new Document();
doc.LoadFromFile("Sample.docx");
//获取第一个section
Section section = doc.Sections[0];
//设置页眉页脚星空最火知名网站不同
section.PageSetup.DifferentFirstPageHeaderFooter = true;
//删除星空最火知名网站页眉页脚
section.HeadersFooters.FirstPageHeader.ChildObjects.Clear();
//保存文档
doc.SaveToFile("Result.docx", FileFormat.Docx);
推荐阅读:【想要快速完成文档格式转换吗?Spire系列组件格式转换完整攻略来啦!】
*购买Spire.Doc正版授权的朋友可以点击哦~~

QQ交谈
在线咨询

渝公网安备
50010702500608号

客服热线