Word文档默认设置每一页的页眉页脚内容都相同。然而在报告、书籍等排版中往往需要不同的页眉页脚来美化排版。本篇文章将分享如何使用C#和免费Word组件-Free Spire.Doc来实现该功能。
该组件为开发人员提供了简便快速的方法来设置页眉页脚首页不同,接下来的部分我将使用它为以下Word文档的首页添加和第二页不同的页眉和页脚。
详细步骤如下:
步骤1:实例化一个Document类的对象document并加载现有word文档。
Document document = new Document();
document.LoadFromFile("SpireDoc.docx");
步骤2:获取该word文档的第一个section,并把它的DifferentFirstPageHeaderFooter属性设置为true。
Section section = document.Sections[0];
section.PageSetup.DifferentFirstPageHeaderFooter = true;
步骤3:设置首页的页眉。这里我们设置了一张图片作为页眉。
Paragraph paragraph1 =section.HeadersFooters.FirstPageHeader.AddParagraph();
paragraph1.Format.HorizontalAlignment = HorizontalAlignment.Left;
paragraph1.AppendPicture(Image.FromFile("Logo.png"));
设置首页的页脚。
Paragraph paragraph2 =section.HeadersFooters.FirstPageFooter.AddParagraph();
paragraph2.Format.HorizontalAlignment = HorizontalAlignment.Right;
TextRange tr2 = paragraph2.AppendText("E-iceblue");
tr2.CharacterFormat.FontSize = 12;
步骤4:为其他页面设置页眉和页脚。如果你只需要第一页有页眉和页脚,则忽略该步骤。
Paragraph paragraph3 =section.HeadersFooters.Header.AddParagraph();
paragraph3.Format.HorizontalAlignment = HorizontalAlignment.Right;
TextRange tr3 = paragraph3.AppendText("产品介绍");
tr3.CharacterFormat.FontSize = 12;
Paragraph paragraph4 =section.HeadersFooters.Footer.AddParagraph();
paragraph4.Format.HorizontalAlignment = HorizontalAlignment.Right;
TextRange tr4 = paragraph4.AppendText("Spire.Doc for .NET");
tr4.CharacterFormat.FontSize = 12;
步骤5:保存文档。
document.SaveToFile("页眉.docx", FileFormat.Docx2010);
运行代码将得到以下结果文档:
完整代码:
using System.Drawing;
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
namespace ConsoleApplication4
{
class Program
{
static void Main(string[] args)
{
Document document = newDocument();
document.LoadFromFile("SpireDoc.docx");
Section section = document.Sections[0];
section.PageSetup.DifferentFirstPageHeaderFooter = true;
Paragraph paragraph1 =section.HeadersFooters.FirstPageHeader.AddParagraph();
paragraph1.Format.HorizontalAlignment = HorizontalAlignment.Left;
paragraph1.AppendPicture(Image.FromFile("Logo.png"));
Paragraph paragraph2 = section.HeadersFooters.FirstPageFooter.AddParagraph();
paragraph2.Format.HorizontalAlignment = HorizontalAlignment.Right;
TextRange tr2 = paragraph2.AppendText("E-iceblue");
tr2.CharacterFormat.FontSize = 12;
Paragraph paragraph3 =section.HeadersFooters.Header.AddParagraph();
paragraph3.Format.HorizontalAlignment = HorizontalAlignment.Right;
TextRange tr3 = paragraph3.AppendText("产品介绍");
tr3.CharacterFormat.FontSize = 12;
Paragraph paragraph4 =section.HeadersFooters.Footer.AddParagraph();
paragraph4.Format.HorizontalAlignment = HorizontalAlignment.Right;
TextRange tr4 = paragraph4.AppendText("Spire.Doc for .NET");
tr4.CharacterFormat.FontSize= 12;
document.SaveToFile("页眉.docx",FileFormat.Docx2010);
System.Diagnostics.Process.Start("页眉.docx");
}
}
}
感谢阅读,希望本文能给您带来帮助!