在Word工具栏里,我们通常会设置页眉,页脚,页码来对word文档进行排版。该文将详细介绍如何使用C#为word文档添加页眉,页脚和页码。
第一部分
如果Word文档包含许多页,我们可以在页眉页脚处添加页码。该页码可显示当前页数, 总页数。我们以在页脚处添加页码为例:
C#
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);
VB.NET
Dim document As Document = New Document
Dim sec As Section = document.AddSection
Dim para As Paragraph = sec.AddParagraph
para.AppendText("Page 1")
para.AppendBreak(BreakType.PageBreak)
para.AppendText("Page 2")
Dim footer As HeaderFooter = sec.HeadersFooters.Footer
Dim footerPara As Paragraph = 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文档添加图文混排的页面页脚。
图片和文字都能被添加为页眉或页脚,我们用C#来为word文档添加图文混排的页眉为例。
C#
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);
VB.NET
Dim document As Document = New Document
Dim sec As Section = document.AddSection
Dim para As Paragraph = sec.AddParagraph
para.AppendText("Page 1")
Dim header As HeaderFooter = sec.HeadersFooters.Header
Dim headerPara As Paragraph = header.AddParagraph
Dim headerImage As DocPicture = headerPara.AppendPicture(Image.FromFile("logo.jpg"))
Dim TR As TextRange = headerPara.AppendText("成都冰蓝科技")
document.SaveToFile("图文页眉".docx", FileFormat.Docx)
页眉效果图:
同时,我们可以通过 TextWrappingStyle 和 TextWrappingType来设置图片在文本中的位置和自动换行:
C#
headerImage.TextWrappingStyle = TextWrappingStyle.Through;
headerImage.TextWrappingType = TextWrappingType.Left;
VB.NET
headerImage.TextWrappingStyle = TextWrappingStyle.Through
headerImage.TextWrappingType = TextWrappingType.Left
第三部分
在C#里实现Word页眉页脚的奇偶页不同和首页不同。主要代码设置如下所示,具体的页眉和页脚步骤参照第二部分,这里不再复述。
C#
sec.PageSetup.DifferentOddAndEvenPagesHeaderFooter = true;
sec.PageSetup.DifferentFirstPageHeaderFooter = true;
VB.NET
sec.PageSetup.DifferentOddAndEvenPagesHeaderFooter = true
sec.PageSetup.DifferentFirstPageHeaderFooter = true