Adjust the Height of Headers and Footers in a Word document in C#
The height of headers and footers can be adjusted by using the HeaderDistance and the FooterDistance properties. The detail steps of how to adjust the height of headers and footers in a word document using Spire.Doc are shown below.
Detail steps:
Step 1: Instantiate a Document object and load the word document.
Document doc = new Document(); doc.LoadFromFile("Headers and Footers.docx");
Step 2: Get the first section.
Section section = doc.Sections[0];
Step 3: Adjust the height of headers and footers in the section.
section.PageSetup.HeaderDistance = 100; section.PageSetup.FooterDistance = 100;
Step 4: Save the file.
doc.SaveToFile("Output.docx", FileFormat.Docx2013);
Screenshot:
Header:
Footer:
Full code:
//Instantiate a Document object Document doc = new Document(); //Load the word document doc.LoadFromFile("Headers and Footers.docx"); //Get the first section Section section = doc.Sections[0]; //Adjust the height of headers in the section section.PageSetup.HeaderDistance = 100; //Adjust the height of footers in the section section.PageSetup.FooterDistance = 100; //Save the document doc.SaveToFile("Output.docx", FileFormat.Docx2013);
Lock the header from editing on word document in C#
With the help of Spire.Doc, we can easily add and remove header on the word documents in C#. This article we will demonstrate how to lock down the header information from editing. We will divide it into two parts for the demo. Once is for locking the header information on the existing word document with header and the other is on the new creating word document.
How to lock the header information on the existing word document.
//Load the sample document with header Document doc = new Document(); doc.LoadFromFile("sample.docx"); //Get the first section from the word document Section section = doc.Sections[0]; //Protect the document and set the ProtectionType as AllowOnlyFormFields doc.Protect(ProtectionType.AllowOnlyFormFields, "123"); //Set the ProtectForm as false to unprotect the section section.ProtectForm = false; //Save the document to file doc.SaveToFile("Result.docx", FileFormat.Docx2013);
Effective screenshot of the header has been locked and the other area can be edited:
How to lock the header information for the new word document.
//Create a new instance of word document Document doc = new Document(); //Add a section to the word document Section section = doc.AddSection(); //Add header information to the section HeaderFooter header = section.HeadersFooters.Header; Paragraph HParagraph = header.AddParagraph(); TextRange HText = HParagraph.AppendText("Protect header"); //Add a paragraph to the section Paragraph Para = section.AddParagraph(); Para.AppendText("Demo of how to lock the header information by Spire.Doc "); //Set the ProtectionType as AllowOnlyFormFields and then unprotect the section doc.Protect(ProtectionType.AllowOnlyFormFields, "123"); section.ProtectForm = false; //Save the document to file doc.SaveToFile("Result.docx", FileFormat.Docx2013);
Copy Header/Footer between Word Documents in C#, VB.NET
When you create several Word documents that are closely related, you may want the header or footer of one document to be used as the header or footer of other documents. For example, you're creating internal documents with your company logo or name or other material been placed in header, you only have to create the header once and copy the header to other places.
In this article, I'll introduce you a simple and efficient solution to copy the entire header (including text and graphic) from one Word document and insert it to another.
Source Document:
Detail Steps:
Step 1: Create a new instance of Document class and load the source file.
Document doc1 = new Document(); doc1.LoadFromFile("test1.docx");
Step 2: Get the header section from the source document.
HeaderFooter header = doc1.Sections[0].HeadersFooters.Header;
Step 3: Initialize a new instance of Document and load another file that you want to insert header.
Document doc2 = new Document("test2.docx");
Step 4: Call DocuentObject.Clone() method to copy each object in the header of source file, then call DocumentObjectCollection.Add() method to insert copied object into the header of destination file.
foreach (Section section in doc2.Sections) { foreach (DocumentObject obj in header.ChildObjects) { section.HeadersFooters.Header.ChildObjects.Add(obj.Clone()); } }
Step 5: Save the changes and launch the file.
doc2.SaveToFile("test2.docx", FileFormat.Docx2013); System.Diagnostics.Process.Start("test2.docx");
Destination Document:
Full Code:
Document doc1 = new Document(); doc1.LoadFromFile("test1.docx"); HeaderFooter header = doc1.Sections[0].HeadersFooters.Header; Document doc2 = new Document("test2.docx"); foreach (Section section in doc2.Sections) { foreach (DocumentObject obj in header.ChildObjects) { section.HeadersFooters.Header.ChildObjects.Add(obj.Clone()); } } doc2.SaveToFile("test2.docx", FileFormat.Docx2013); System.Diagnostics.Process.Start("test2.docx");
Dim doc1 As New Document() doc1.LoadFromFile("test1.docx") Dim header As HeaderFooter = doc1.Sections(0).HeadersFooters.Header Dim doc2 As New Document("test2.docx") For Each section As Section In doc2.Sections For Each obj As DocumentObject In header.ChildObjects section.HeadersFooters.Header.ChildObjects.Add(obj.Clone()) Next Next doc2.SaveToFile("test2.docx", FileFormat.Docx2013) System.Diagnostics.Process.Start("test2.docx")
Set whether page border surrounds header/footer or not
In MS Word page border options, there are checkboxes to choose whether page border surrounds header/footer or not. This feature is very important for which can be used to manage the positional relation between page border and header/footer. Spire.Doc supports to set the two frequently-used features: page border and header/footer, and it supports to manage their spatial relations, too. This article is going to introduce the method to set whether page border surrounds header/footer or not.
Note: before start, please download the latest version of Spire.Doc and add the .dll in the bin folder as the reference of Visual Studio.
Step 1: Create a Word document and add a section.
Document document = new Document(); Section section = document.AddSection();
Step 2: Add a sample page border to the document using Spire.Doc library.
section.PageSetup.Borders.BorderType = BorderStyle.Wave; section.PageSetup.Borders.Color = Color.Green; section.PageSetup.Borders.Left.Space = 20; section.PageSetup.Borders.Right.Space = 20;
Step 3: Add sample header and footer to the document using Spire.Doc library.
//add a header and set its format Paragraph paragraph1 = section.HeadersFooters.Header.AddParagraph(); paragraph1.Format.HorizontalAlignment = HorizontalAlignment.Right; TextRange headerText = paragraph1.AppendText("Header isn't included in page border"); headerText.CharacterFormat.FontName = "Calibri"; headerText.CharacterFormat.FontSize = 20; headerText.CharacterFormat.Bold = true; //add a footer and set its format Paragraph paragraph2 = section.HeadersFooters.Footer.AddParagraph(); paragraph2.Format.HorizontalAlignment = HorizontalAlignment.Left; TextRange footerText = paragraph2.AppendText("Footer is included in page border"); footerText.CharacterFormat.FontName = "Calibri"; footerText.CharacterFormat.FontSize = 20; footerText.CharacterFormat.Bold = true;
Step 4: Set the header not included in the page border while the footer included.
section.PageSetup.PageBorderIncludeHeader = false; section.PageSetup.HeaderDistance = 40; section.PageSetup.PageBorderIncludeFooter = true; section.PageSetup.FooterDistance = 40;
Step 5: Save the document and launch to see effect.
document.SaveToFile("result.docx", FileFormat.Docx2013); System.Diagnostics.Process.Start("result.docx");
Effects:
Full Codes:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Spire.Doc; using Spire.Doc.Documents; using Spire.Doc.Fields; using System.Drawing; namespace Mirror_Margin { class Program { static void Main(string[] args) { Document document = new Document(); Section section = document.AddSection(); section.PageSetup.Borders.BorderType = BorderStyle.Wave; section.PageSetup.Borders.Color = Color.Green; section.PageSetup.Borders.Left.Space = 20; section.PageSetup.Borders.Right.Space = 20; Paragraph paragraph1 = section.HeadersFooters.Header.AddParagraph(); paragraph1.Format.HorizontalAlignment = HorizontalAlignment.Right; TextRange headerText = paragraph1.AppendText("Header isn't included in page border"); headerText.CharacterFormat.FontName = "Calibri"; headerText.CharacterFormat.FontSize = 20; headerText.CharacterFormat.Bold = true; Paragraph paragraph2 = section.HeadersFooters.Footer.AddParagraph(); paragraph2.Format.HorizontalAlignment = HorizontalAlignment.Left; TextRange footerText = paragraph2.AppendText("Footer is included in page border"); footerText.CharacterFormat.FontName = "Calibri"; footerText.CharacterFormat.FontSize = 20; footerText.CharacterFormat.Bold = true; section.PageSetup.PageBorderIncludeHeader = false; section.PageSetup.HeaderDistance = 40; section.PageSetup.PageBorderIncludeFooter = true; section.PageSetup.FooterDistance = 40; document.SaveToFile("result.docx", FileFormat.Docx2013); System.Diagnostics.Process.Start("result.docx"); } } }
Add different first page header and footer
In the MS Word Header & Footer Tools options, we could choose "Different First Page" and "Different odd and even pages". The article "How to create different headers/footers for odd and even pages" introduces the method to set different odd and even pages using Spire.Doc. Spire.DOC also provides an easy and quick method to add different first page header & footer. This article is going to introduce the method to add different first page header & footer.
FYI, if you only need the first page header and footer, please just set the first page header & footer and leave the rest alone. In this way, your Word document will only have header & footer in the first page, which provides a simpler way to add a header only into the first page of a document than the method mentioned in the article "How to add a header only into the first page of a document".
Note: before start, please download the latest version of Spire.Doc and add Spire.Doc .dll in the bin folder as the reference of Visual Studio.
Step 1: Load the sample document that only contains text.
Document document = new Document(); document.LoadFromFile("T.docx");
Step 2: Get the section and set the property true.
Section section = document.Sections[0]; section.PageSetup.DifferentFirstPageHeaderFooter = true;
Step 3: Set the first page header. Here we append a picture as the header.
Paragraph paragraph1 = section.HeadersFooters.FirstPageHeader.AddParagraph(); paragraph1.Format.HorizontalAlignment = HorizontalAlignment.Right; DocPicture headerimage = paragraph1.AppendPicture(Image.FromFile("2.bmp"));
Step 4: Set the first page footer.
Paragraph paragraph2 = section.HeadersFooters.FirstPageFooter.AddParagraph(); paragraph2.Format.HorizontalAlignment = HorizontalAlignment.Center; TextRange FF = paragraph2.AppendText("First Page Footer"); FF.CharacterFormat.FontSize = 20;
Step 5: Set the other header & footer. If you only need the first page header & footer, don't set this.
Paragraph paragraph3 = section.HeadersFooters.Header.AddParagraph(); paragraph3.Format.HorizontalAlignment = HorizontalAlignment.Center; TextRange NH = paragraph3.AppendText("If you only need first page header, don't set this."); NH.CharacterFormat.FontSize = 20; Paragraph paragraph4 = section.HeadersFooters.Footer.AddParagraph(); paragraph4.Format.HorizontalAlignment = HorizontalAlignment.Center; TextRange NF = paragraph4.AppendText("If you only need first page footer, don't set this."); NF.CharacterFormat.FontSize = 20;
Step 6: save the document and launch to see effects.
document.SaveToFile("R.docx", FileFormat.Docx2010); System.Diagnostics.Process.Start("R.docx");
Effects:
Full codes:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Spire.Doc; using Spire.Doc.Documents; using Spire.Doc.Fields; using System.Drawing; namespace Mirror_Margin { class Program { static void Main(string[] args) { Document document = new Document(); document.LoadFromFile("T.docx"); Section section = document.Sections[0]; section.PageSetup.DifferentFirstPageHeaderFooter = true; Paragraph paragraph1 = section.HeadersFooters.FirstPageHeader.AddParagraph(); paragraph1.Format.HorizontalAlignment = HorizontalAlignment.Right; DocPicture headerimage = paragraph1.AppendPicture(Image.FromFile("2.bmp")); Paragraph paragraph2 = section.HeadersFooters.FirstPageFooter.AddParagraph(); paragraph2.Format.HorizontalAlignment = HorizontalAlignment.Center; TextRange FF = paragraph2.AppendText("First Page Footer"); FF.CharacterFormat.FontSize = 20; Paragraph paragraph3 = section.HeadersFooters.Header.AddParagraph(); paragraph3.Format.HorizontalAlignment = HorizontalAlignment.Center; TextRange NH = paragraph3.AppendText("If you only need first page header, don't set this."); NH.CharacterFormat.FontSize = 20; Paragraph paragraph4 = section.HeadersFooters.Footer.AddParagraph(); paragraph4.Format.HorizontalAlignment = HorizontalAlignment.Center; TextRange NF = paragraph4.AppendText("If you only need first page footer, don't set this."); NF.CharacterFormat.FontSize = 20; document.SaveToFile("R.docx", FileFormat.Docx2010); System.Diagnostics.Process.Start("R.docx"); } } }
Create different headers/footers for odd and even pages
Headers and footers are widely used to show addition information such as chapter name, page numbers to keep the document organized. By default, MS Word sets the same headers and footers on each page, but sometimes we need to create different headers or footers for odd and even pages. This article is going to introduce the method to set different odd and even header/footer using Spire.Doc in C#.
Note: Before Start, please download the latest version of Spire.Doc and add Spire.Doc .dll in the bin folder as the reference of Visual Studio.
Step 1: Create a new document and load from file.
Document document = new Document(); document.LoadFromFile("T1.docx");
Step 2: Add a section and set the property true.
Section section = document.Sections[0]; section.PageSetup.DifferentOddAndEvenPagesHeaderFooter = true;
Step 3: Create odd and even footer, odd and even header, and set their format.
//add EvenFooter Paragraph P1 = section.HeadersFooters.EvenFooter.AddParagraph(); TextRange EF = P1.AppendText("Even Footer Demo from E-iceblue Using Spire.Doc"); EF.CharacterFormat.FontName = "Calibri"; EF.CharacterFormat.FontSize = 20; EF.CharacterFormat.TextColor = Color.Green; EF.CharacterFormat.Bold = true; P1.Format.HorizontalAlignment = HorizontalAlignment.Center; //add OddFooter Paragraph P2 = section.HeadersFooters.OddFooter.AddParagraph(); TextRange OF = P2.AppendText("Odd Footer Demo"); P2.Format.HorizontalAlignment = HorizontalAlignment.Center; OF.CharacterFormat.FontName = "Calibri"; OF.CharacterFormat.FontSize = 20; OF.CharacterFormat.Bold = true; OF.CharacterFormat.TextColor = Color.Blue; //add OddHeader Paragraph P3 = section.HeadersFooters.OddHeader.AddParagraph(); TextRange OH = P3.AppendText("Odd Header Demo"); P3.Format.HorizontalAlignment = HorizontalAlignment.Center; OH.CharacterFormat.FontName = "Calibri"; OH.CharacterFormat.FontSize = 20; OH.CharacterFormat.Bold = true; OH.CharacterFormat.TextColor = Color.Blue; //add EvenHeader Paragraph P4 = section.HeadersFooters.EvenHeader.AddParagraph(); TextRange EH = P4.AppendText("Even Header Demo from E-iceblue Using Spire.Doc"); P4.Format.HorizontalAlignment = HorizontalAlignment.Center; EH.CharacterFormat.FontName = "Calibri"; EH.CharacterFormat.FontSize = 20; EH.CharacterFormat.Bold = true; EH.CharacterFormat.TextColor = Color.Green;
Step 4: Save the document and launch to see effects.
document.SaveToFile("R.docx", FileFormat.Docx2010); System.Diagnostics.Process.Start("R.docx");
Effects:
Full code:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Spire.Doc; using Spire.Doc.Documents; using Spire.Doc.Fields; using System.Drawing; namespace Mirror_Margin { class Program { static void Main(string[] args) { Document document = new Document(); document.LoadFromFile("T1.docx"); Section section = document.Sections[0]; section.PageSetup.DifferentOddAndEvenPagesHeaderFooter = true; Paragraph P1 = section.HeadersFooters.EvenFooter.AddParagraph(); TextRange EF = P1.AppendText("Even Footer Demo from E-iceblue Using Spire.Doc"); EF.CharacterFormat.FontName = "Calibri"; EF.CharacterFormat.FontSize = 20; EF.CharacterFormat.TextColor = Color.Green; EF.CharacterFormat.Bold = true; P1.Format.HorizontalAlignment = HorizontalAlignment.Center; Paragraph P2 = section.HeadersFooters.OddFooter.AddParagraph(); TextRange OF = P2.AppendText("Odd Footer Demo"); P2.Format.HorizontalAlignment = HorizontalAlignment.Center; OF.CharacterFormat.FontName = "Calibri"; OF.CharacterFormat.FontSize = 20; OF.CharacterFormat.Bold = true; OF.CharacterFormat.TextColor = Color.Blue; Paragraph P3 = section.HeadersFooters.OddHeader.AddParagraph(); TextRange OH = P3.AppendText("Odd Header Demo"); P3.Format.HorizontalAlignment = HorizontalAlignment.Center; OH.CharacterFormat.FontName = "Calibri"; OH.CharacterFormat.FontSize = 20; OH.CharacterFormat.Bold = true; OH.CharacterFormat.TextColor = Color.Blue; Paragraph P4 = section.HeadersFooters.EvenHeader.AddParagraph(); TextRange EH = P4.AppendText("Even Header Demo from E-iceblue Using Spire.Doc"); P4.Format.HorizontalAlignment = HorizontalAlignment.Center; EH.CharacterFormat.FontName = "Calibri"; EH.CharacterFormat.FontSize = 20; EH.CharacterFormat.Bold = true; EH.CharacterFormat.TextColor = Color.Green; document.SaveToFile("R.docx", FileFormat.Docx2010); System.Diagnostics.Process.Start("R.docx"); } } }
C#: Add Page Numbers to a Word Document
Adding page numbers to your Word documents can enhance their organization and readability. Page numbers provide a convenient reference point for readers and make it easier to navigate through lengthy documents. Whether you're working on a report, thesis, or any other document, incorporating page numbers is a simple yet effective way to improve its overall structure and accessibility.
In this article, you will learn how to add page numbers to a Word document in C# by using the Spire.Doc for .NET library.
- Add Page Numbers to a Word Document
- Add Page Numbers to a Specific Section in a Word Document
- Add Different Page Numbers to Different Sections in a Word Document
Install Spire.Doc for .NET
To begin with, you need to add the DLL files included in the Spire.Doc for.NET package as references in your .NET project. The DLL files can be either downloaded from this link or installed via NuGet.
PM> Install-Package Spire.Doc
Add Page Numbers to a Word Document in C#
To achieve the dynamic addition of page numbers to a Word document, Spire.Doc for .NET offers a range of fields, including FieldPage, FieldNumPages, and FieldSectionPages. These fields act as placeholders for the current page number, total page count, and section page count, allowing you to customize and automate the display of page numbers in your document.
To incorporate these placeholders (usually in the header or footer section) within your Word document, you can utilize the Paragraph.AppendField() method.
The following steps outline how to add a FieldPage field and a FieldNumPages field in the footer, resulting in the display of "X/Y" format in the document.
- Create a Document object.
- Load a Word document from a specified file path.
- Get the first section using Document.Sections[index] property
- Get the footer of the first section using Section.HeadersFooters.Footer property.
- Add a paragraph to the footer using HeaderFooter.AddParagraph() method.
- Insert a FieldPage field, a FieldNumPages field and a "/" to the paragraph using Paragraph.AppendField() and Parargph.AppendText() methods.
- Save the document to a different Word file.
- C#
using Spire.Doc; using Spire.Doc.Documents; using System.Drawing; namespace AddPageNumbersToDocument { class Program { static void Main(string[] args) { // Create a Document object Document document = new Document(); // Load a Word file document.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Privacy Policy.docx"); // Get the first section Section section = document.Sections[0]; // Get the footer of the section HeaderFooter footer = section.HeadersFooters.Footer; // Add "page number / page count" to the footer Paragraph footerParagraph = footer.AddParagraph(); footerParagraph.AppendField("page number", FieldType.FieldPage); footerParagraph.AppendText(" / "); footerParagraph.AppendField("page count", FieldType.FieldNumPages); footerParagraph.Format.HorizontalAlignment = HorizontalAlignment.Center; // Apply formatting to the page number ParagraphStyle style = new ParagraphStyle(document); style.CharacterFormat.Bold = true; style.CharacterFormat.FontName = "Times New Roman"; style.CharacterFormat.FontSize = 18; style.CharacterFormat.TextColor = Color.Red; document.Styles.Add(style); footerParagraph.ApplyStyle(style); // Save the document document.SaveToFile("AddPageNumbersToDocument.docx"); // Dispose resources document.Dispose(); } } }
Add Page Numbers to a Specific Section in a Word Document in C#
By default, page numbers in the footer of a section are automatically linked to the previous section, ensuring a continuous display. However, if you wish to add page numbers to a specific section only, you need to unlink the subsequent section from the previous section and remove the content of the footers in the subsequent sections.
The following are the steps to add page numbers to a specific section in a Word document using Spire.Doc for .NET.
- Create a Document object.
- Load a Word document from a specified file path.
- Get a specific section using Document.Sections[index] property
- Get the footer of the section using Section.HeadersFooters.Footer property.
- Restart page numbering from 1 by setting Section.PageSetup.RestartPageNumbering property to true and Section.PageSetup.PageStartingNumber property to 1.
- Insert a FieldPage field, a FieldSectionPages field and a "/" to the footer using Paragraph.AppendField() and Parargph.AppendText() methods.
- Disable "Link to previous" by setting HeadersFooters.Footer.LinkToPrevious propety to false.
- Delete the content of the footers in the subsequent sections
- Save the document to a different Word file.
- C#
using Spire.Doc; using Spire.Doc.Documents; using System.Drawing; namespace AddPageNumbersToSpecificSection { class Program { static void Main(string[] args) { // Create a Document object Document document = new Document(); // Load a Word file document.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Privacy Policy.docx"); // Get a specific section int sectionIndex = 1; Section section = document.Sections[sectionIndex]; // Restart page numbering from 1 section.PageSetup.RestartPageNumbering = true; section.PageSetup.PageStartingNumber = 1; // Get the footer of the section HeaderFooter footer = section.HeadersFooters.Footer; // Add "page number / page count" to the footer Paragraph footerParagraph = footer.AddParagraph(); footerParagraph.AppendField("page number", FieldType.FieldPage); footerParagraph.AppendText(" / "); footerParagraph.AppendField("page count", FieldType.FieldSectionPages); footerParagraph.Format.HorizontalAlignment = HorizontalAlignment.Center; // Apply formatting to the page number ParagraphStyle style = new ParagraphStyle(document); style.CharacterFormat.Bold = true; style.CharacterFormat.FontName = "Times New Roman"; style.CharacterFormat.FontSize = 18; style.CharacterFormat.TextColor = Color.Red; document.Styles.Add(style); footerParagraph.ApplyStyle(style); // Disable "Link to previous" in the subsequent section document.Sections[sectionIndex + 1].HeadersFooters.Footer.LinkToPrevious = false; // Delete the content of the footers in the subsequent sections for (int i = sectionIndex + 1; i < document.Sections.Count; i++) { document.Sections[i].HeadersFooters.Footer.ChildObjects.Clear(); document.Sections[i].HeadersFooters.Footer.AddParagraph(); } // Save the document document.SaveToFile("AddPageNumbersToSection.docx"); // Dispose resources document.Dispose(); } } }
Add Different Page Numbers to Different Sections in a Word Document in C#
To ensure that different sections have distinct page numbers, you need to get each section in the document, add page numbers to them separately, and restart page numbering from 1 at the beginning of each section.
The following are detailed steps.
- Create a Document object.
- Load a Word document from a specified file path.
- Iterate through the sections in the document.
- Get a specific section using Document.Sections[index] property
- Get the footer of the section using Section.HeadersFooters.Footer property.
- Restart page numbering from 1 by setting Section.PageSetup.RestartPageNumbering property to true and Section.PageSetup.PageStartingNumber property to 1.
- Insert a FieldPage field, a FieldSectionPages field and a "/" to the footer using Paragraph.AppendField() and Parargph.AppendText() methods.
- Save the document to a different Word file.
- C#
using Spire.Doc; using Spire.Doc.Documents; using System.Drawing; namespace AddDifferentPageNumbersToDifferentSections { class Program { static void Main(string[] args) { // Create a Document object Document document = new Document(); // Load a Word file document.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Privacy Policy.docx"); // Iterate through the sections in the document for (int i = 0; i < document.Sections.Count; i++) { // Get a specific section Section section = document.Sections[i]; // Restart page numbering from 1 section.PageSetup.RestartPageNumbering = true; section.PageSetup.PageStartingNumber = 1; // Get the footer of the section HeaderFooter footer = section.HeadersFooters.Footer; // Add "page number / page count" to the footer Paragraph footerParagraph = footer.AddParagraph(); footerParagraph.AppendField("page number", FieldType.FieldPage); footerParagraph.AppendText(" / "); footerParagraph.AppendField("page count", FieldType.FieldSectionPages); footerParagraph.Format.HorizontalAlignment = HorizontalAlignment.Center; // Apply formatting to the page number ParagraphStyle style = new ParagraphStyle(document); style.CharacterFormat.Bold = true; style.CharacterFormat.FontName = "Times New Roman"; style.CharacterFormat.FontSize = 18; style.CharacterFormat.TextColor = Color.Red; document.Styles.Add(style); footerParagraph.ApplyStyle(style); } // Save the document document.SaveToFile("AddDifferentPageNumbersToSections.docx"); // Dispose resources document.Dispose(); } } }
Apply for a Temporary License
If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.
C#: Remove Headers or Footers in Word
If the headers or footers in a Word document contains unnecessary information, such as outdated version numbers, redundant company logos, or incorrect author names, removing them can make the document look more professional and concise. In this article, you will learn how to remove headers or footers in Word in C# using Spire.Doc for .NET.
Install Spire.Doc for .NET
To begin with, you need to add the DLL files included in the Spire.Doc for.NET package as references in your .NET project. The DLL files can be either downloaded from this link or installed via NuGet.
PM> Install-Package Spire.Doc
Remove Headers in Word in C#
Spire.Doc for .NET supports getting different headers in the first pages, odd pages, and even pages, and then delete all of them through the HeaderFooter.ChildObjects.Clear() method. The following are the detailed steps:
- Create a Document instance.
- Load a Word document using Document.LoadFromFile() method.
- Get a specified section using Document.Sections[] property.
- Iterate through all paragraphs in the section, and then all child objects in each paragraph.
- Get the headers for the first, odd, and even pages using Section.HeadersFooters[HeaderFooterType hfType] property, and then delete them using HeaderFooter.ChildObjects.Clear() method.
- Save the result document using Document.SaveToFile() method.
- C#
using Spire.Doc; using Spire.Doc.Documents; namespace RemoveHeader { class Program { static void Main(string[] args) { //Create a Document instance Document doc = new Document(); //Load a Word document doc.LoadFromFile("HeaderFooter.docx"); //Get the first section Section section = doc.Sections[0]; //Iterate through all paragraphs in the section foreach (Paragraph para in section.Paragraphs) { //Iterate through all child objects in each paragraph foreach (DocumentObject obj in para.ChildObjects) { //Delete header in the first page HeaderFooter header; header = section.HeadersFooters[HeaderFooterType.HeaderFirstPage]; if (header != null) header.ChildObjects.Clear(); //Delete headers in the odd pages header = section.HeadersFooters[HeaderFooterType.HeaderOdd]; if (header != null) header.ChildObjects.Clear(); //Delete headers in the even pages header = section.HeadersFooters[HeaderFooterType.HeaderEven]; if (header != null) header.ChildObjects.Clear(); } } //Save the result document doc.SaveToFile("RemoveHeader.docx", FileFormat.Docx); } } }
Remove Footers in Word in C#
Deleting footers is similar to that of deleting headers, you can also get the footers on different pages first and then delete them at once. The following are the detailed steps:
- Create a Document instance.
- Load a Word document using Document.LoadFromFile() method.
- Get a specified section using Document.Sections[] property.
- Iterate through all paragraphs in the section, and then all child objects in each paragraph.
- Get the footers for the first, odd, and even pages using Section.HeadersFooters[HeaderFooterType hfType] property, and then delete them using HeaderFooter.ChildObjects.Clear() method.
- Save the result document using Document.SaveToFile() method.
- C#
using Spire.Doc; using Spire.Doc.Documents; namespace RemoveHeader { class Program { static void Main(string[] args) { //Create a Document instance Document doc = new Document(); //Load a Word document doc.LoadFromFile("HeaderFooter.docx"); //Get the first section Section section = doc.Sections[0]; //Iterate through all paragraphs in the section foreach (Paragraph para in section.Paragraphs) { //Iterate through all child objects in each paragraph foreach (DocumentObject obj in para.ChildObjects) { //Delete footer in the first page HeaderFooter footer; footer = section.HeadersFooters[HeaderFooterType.FooterFirstPage]; if (footer != null) footer.ChildObjects.Clear(); //Delete footer in the odd page footer = section.HeadersFooters[HeaderFooterType.FooterOdd]; if (footer != null) footer.ChildObjects.Clear(); //Delete footer in the even page footer = section.HeadersFooters[HeaderFooterType.FooterEven]; if (footer != null) footer.ChildObjects.Clear(); } } //Save the result document doc.SaveToFile("RemoveFooter.docx", FileFormat.Docx); } } }
Apply for a Temporary License
If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.
Add a header only into the first page of a document
A document can have one or more pages. It is probably easy to add a header for all pages of the document. If you want to add the header only for the first page of the document, Spire.Doc for .NET component can provide you an easy and flexible solution to handle it. The following steps will guide how to add a header into the first page of a document using Spire.Doc for .NET component in C#. In the example, the header is got from an existing document.
Step 1: Load a word document, documen1.docx.
Document document1 = new Document(); document1.LoadFromFile("D:\\document1.docx");
Step 2: Get the header of document1.docx.
HeaderFooter header = document1.Sections[0].HeadersFooters.Header;
Step 3: Load another word document which will be added the header, document2.docx.
Document document2 = new Document(); document2.LoadFromFile("D:\\document2.docx");
Step 4: Get the first page header of document2.docx.
HeaderFooter firstPageHeader = document2.Sections[0].HeadersFooters.FirstPageHeader;
Step 5: Specify that the current section has a different header/footer for the first page.
foreach (Section section in document2.Sections) { section.PageSetup.DifferentFirstPageHeaderFooter = true; }
Step 6: Removes all child objects in firstPageHeader.
firstPageHeader.Paragraphs.Clear();
Step 7: Add all child objects of the header to firstPageHeader.
foreach (DocumentObject obj in header.ChildObjects) { firstPageHeader.ChildObjects.Add(obj.Clone()); }
Step 8: Save document2.docx to a new document, header.docx.
document2.SaveToFile("D:\\Header.docx"", FileFormat.Docx);
Full code:
Document document1 = new Document(); document1.LoadFromFile(@"..\..\document1.docx"); Document document2 = new Document(); document2.LoadFromFile(@"..\..\document2.docx"); HeaderFooter header = document1.Sections[0].HeadersFooters.Header; HeaderFooter firstPageHeader = document2.Sections[0].HeadersFooters.FirstPageHeader; foreach (Section section in document2.Sections) { section.PageSetup.DifferentFirstPageHeaderFooter = true; } firstPageHeader.Paragraphs.Clear(); foreach (DocumentObject obj in header.ChildObjects) { firstPageHeader.ChildObjects.Add(obj.Clone()); } document2.SaveToFile("Header.docx", FileFormat.Docx);
Screenshots:
document1.docx:
document2.docx:
Header.docx:
Insert Image Header and Footer for Word
Word header and footer presents additional information of Word document, which can be text, image or page number. This guide focuses on introducing how to insert image header and footer for Word document in C# and VB.NET.
Header/Footer plays an important role in Word document, which uses text, image or page number to demonstrate some additional information about this document. The information can be company name, logo, author name, document title etc. This guide will demonstrate detailed process to insert image header/footer in Word with C# and VB.NET via Spire.Doc for .NET. The following screenshot displays Word image header/footer result after programming.
Spire.Doc for .NET provides a HeaderFooter. class to enable developers to generate a new header or footer. Firstly, initialize a header instance of HeaderFooter class and then invoke AddParagraph() method to add a paragraph body for this header/footer instance. Next, invoke Paragraph.AppendPicture(Image image) method to append a picture for header/footer paragraph. If you want to add text for paragraph as well, please invoke Paragraph.AppendText(string text) method. Also, you can set format for header/footer paragraph, appended image and text to have a better layout. Code as following:
using System.Drawing; using Spire.Doc; using Spire.Doc.Documents; using Spire.Doc.Fields; namespace ImageHeaderFooter { class Program { static void Main(string[] args) { //Load Document Document document = new Document(); document.LoadFromFile(@"E:\Work\Documents\Spire.Doc for .NET.docx"); //Initialize a Header Instance HeaderFooter header = document.Sections[0].HeadersFooters.Header; //Add Header Paragraph and Format Paragraph paragraph = header.AddParagraph(); paragraph.Format.HorizontalAlignment = HorizontalAlignment.Right; //Append Picture for Header Paragraph and Format DocPicture headerimage = paragraph.AppendPicture(Image.FromFile(@"E:\Logo\doclog.png")); headerimage.VerticalAlignment = ShapeVerticalAlignment.Bottom; //Initialize a Footer Instance HeaderFooter footer = document.Sections[0].HeadersFooters.Footer; //Add Footer Paragraph and Format Paragraph paragraph2 = footer.AddParagraph(); paragraph2.Format.HorizontalAlignment = HorizontalAlignment.Left; //Append Picture and Text for Footer Paragraph DocPicture footerimage = paragraph2.AppendPicture(Image.FromFile(@"E:\Logo\logo.jpeg")); TextRange TR = paragraph2.AppendText("Copyright © 2013 e-iceblue. All Rights Reserved."); TR.CharacterFormat.FontName = "Arial"; TR.CharacterFormat.FontSize = 10; TR.CharacterFormat.TextColor = Color.Black; //Save and Launch document.SaveToFile("ImageHeaderFooter.docx", FileFormat.Docx); System.Diagnostics.Process.Start("ImageHeaderFooter.docx"); } } }
Imports System.Drawing Imports Spire.Doc Imports Spire.Doc.Documents Imports Spire.Doc.Fields Namespace ImageHeaderFooter Friend Class Program Shared Sub Main(ByVal args() As String) 'Load Document Dim document As New Document() document.LoadFromFile("E:\Work\Documents\Spire.Doc for .NET.docx") 'Initialize a Header Instance Dim header As HeaderFooter = document.Sections(0).HeadersFooters.Header 'Add Header Paragraph and Format Dim paragraph As Paragraph = header.AddParagraph() paragraph.Format.HorizontalAlignment = HorizontalAlignment.Right 'Append Picture for Header Paragraph and Format Dim headerimage As DocPicture = paragraph.AppendPicture(Image.FromFile("E:\Logo\doclog.png")) headerimage.VerticalAlignment = ShapeVerticalAlignment.Bottom 'Initialize a Footer Instance Dim footer As HeaderFooter = document.Sections(0).HeadersFooters.Footer 'Add Footer Paragraph and Format Dim paragraph2 As Paragraph = footer.AddParagraph() paragraph2.Format.HorizontalAlignment = HorizontalAlignment.Left 'Append Picture and Text for Footer Paragraph Dim footerimage As DocPicture = paragraph2.AppendPicture(Image.FromFile("E:\Logo\logo.jpeg")) Dim TR As TextRange = paragraph2.AppendText("Copyright © 2013 e-iceblue. All Rights Reserved.") TR.CharacterFormat.FontName = "Arial" TR.CharacterFormat.FontSize = 10 TR.CharacterFormat.TextColor = Color.Black 'Save and Launch document.SaveToFile("ImageHeaderFooter.docx", FileFormat.Docx) System.Diagnostics.Process.Start("ImageHeaderFooter.docx") End Sub End Class End Namespace
Spire.Doc, an easy-to-use component to perform Word tasks, allows developers to fast generate, write, edit and save Word (Word 97-2003, Word 2007, Word 2010) in C# and VB.NET for .NET, Silverlight and WPF.