In Word documents, you can add time, date, title, reference information, page number, content description and image /logo in header or footer to enrich the document. This article shows how to add headers and footers in C# and VB.NET applications 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 DLLs files can be either downloaded from this link or installed via NuGet.

  • Package Manager
PM> Install-Package Spire.Doc

Add Header and Footer

The table gives a list of main classes, properties and methods used in the operation.

Name Description
Document Class Represents a Word document model.
Document. LoadFromFile() Method Load a Word document.
Section Class Represents a section in a Word document.
Document.Sections Property Gets document sections.
HeaderFooter Class Represents a header and footer model for Word.
Section.HeadersFooters.Header Property Gets headers/footers of current section.
Paragraph Class Represents a paragraph in a document.
HeaderFooter. AddParagraph() Method Adds paragraph at end of section.
TextRange Class Represents a text range.
Paragraph.AppendText() Method Appends text to the end of paragraph.
Document. SaveToFile() Method Saves the document to file in Microsoft Word or another file format.

The following are the steps about adding header and footer.

  • C#
  • VB.NET
using Spire.Doc;
using Spire.Doc.Documents;
using System.Drawing;
using Spire.Doc.Fields;

namespace AddHeaderAndFooter
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create an instance of Document class
            Document document = new Document();

            //Load a Word document
            document.LoadFromFile("input.docx");

            //Get the first section of Word Document
            Section section = document.Sections[0];

            //Get header via HeadersFooters.Header property 
            HeaderFooter header = section.HeadersFooters.Header;

            //Add a paragraph and set paragraph alignment style
            Paragraph headerPara = header.AddParagraph();
            headerPara.Format.HorizontalAlignment = HorizontalAlignment.Left;
            
            //Append text and set font name, size, color,etc.
            TextRange textrange = headerPara.AppendText("E-iceblue Co. Ltd." + "\n Your Office Development Master");
            textrange.CharacterFormat.FontName = "Arial";
            textrange.CharacterFormat.FontSize = 13;
            textrange.CharacterFormat.TextColor = Color.DodgerBlue;
            textrange.CharacterFormat.Bold = true;  
            
            //Get footer, add paragraph and append text
            HeaderFooter footer = section.HeadersFooters.Footer;
            Paragraph footerPara = footer.AddParagraph();
            footerPara.Format.HorizontalAlignment = HorizontalAlignment.Center;
            textrange = footerPara.AppendText("Copyright © 2021  All Rights Reserved.");
            textrange.CharacterFormat.Bold = false;
            textrange.CharacterFormat.FontSize = 11;        
            
            //Save to file
            document.SaveToFile("output.docx", FileFormat.Docx);
        }
    }
}
Imports Spire.Doc
Imports Spire.Doc.Documents
Imports System.Drawing
Imports Spire.Doc.Fields

Namespace AddHeaderAndFooter
	Class Program
		Private Shared Sub Main(args As String())
			'Create an instance of Document class
			Dim document As New Document()

			'Load a Word document
			document.LoadFromFile("input.docx")

			'Get the first section of Word Document
			Dim section As Section = document.Sections(0)

			'Get header via HeadersFooters.Header property 
			Dim header As HeaderFooter = section.HeadersFooters.Header

			'Add a paragraph and set paragraph alignment style
			Dim headerPara As Paragraph = header.AddParagraph()
			headerPara.Format.HorizontalAlignment = HorizontalAlignment.Left

			'Append text and set font name, size, color ,etc.
			Dim textrange As TextRange = headerPara.AppendText("E-iceblue Co. Ltd." + vbLf & " Your Office Development Master")
			textrange.CharacterFormat.FontName = "Arial"
			textrange.CharacterFormat.FontSize = 13
			textrange.CharacterFormat.TextColor = Color.DodgerBlue
			textrange.CharacterFormat.Bold = True


			'Get footer, add paragraph and append text
			Dim footer As HeaderFooter = section.HeadersFooters.Footer
			Dim footerPara As Paragraph = footer.AddParagraph()
			footerPara.Format.HorizontalAlignment = HorizontalAlignment.Center
			textrange = footerPara.AppendText("Copyright © 2021  All Rights Reserved.")
			textrange.CharacterFormat.Bold = False
			textrange.CharacterFormat.FontSize = 11

			'Save to file
			document.SaveToFile("output.docx", FileFormat.Docx)
		End Sub
	End Class
End Namespace

C#/VB.NET: Add Header and Footer in Word Documents

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 Images to Word Documents in .NET

Adding images to Word documents programmatically is a common requirement in document automation. Whether you're generating reports, creating invoices, or building dynamic documents, inserting and customizing images can enhance your document's visual appeal.

In this article, we'll explore how to insert images into Word documents using Spire.Doc for .NET, covering local files, byte arrays, and advanced image customization.

.NET Library for Adding Images to Word

Spire.Doc for .NET is a powerful library that enables developers to create, edit, and manipulate Word documents without Microsoft Office dependencies. It provides straightforward methods to insert and format images in Word files.

Key Features:

  • Insert images from local storage or byte arrays.
  • Adjust image size, rotation, and positioning.
  • Control text wrapping around images.
  • Support for various image formats (PNG, JPG, BMP, etc.).

To get started, downoad Spire.Doc from our offical website and reference the DLLs in your project. Or, you can install it via NuGet through the following command:

PM> Install-Package Spire.Doc

Insert an Imge from Local to Word

The simplest method for inserting images into a Word document is to load them directly from your file system. Using Spire.Doc's AppendPicture() method, you can easily specify the file path of the image. This method automatically detects the image format and embeds it into the document.

using Spire.Doc;
using Spire.Doc.Documents;

namespace InsertImageFromLocal
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a Document object
            Document document = new Document();

            // Add a section
            Section section = document.AddSection();

            // Add a paragraph
            Paragraph paragraph = section.AddParagraph();

            // Append a picture from the local disk
            paragraph.AppendPicture("C:\\Users\\Administrator\\Desktop\\MyPic.png");

            // Save the document
            document.SaveToFile("output.docx", FileFormat.Docx);

            // Dispose resources
            document.Dispose();
        }
    }
}

Insert Images to Word in C#

Insert an Image from a Byte Array to Word

In dynamic applications, integrating images from web sources or databases is often essential for enhancing user experience and content relevance.This method downloads images as byte arrays and injecte into the document using a MemoryStream .

By utilizing this technique, developers can dynamically populate documents with up-to-date content, such as logos or product images, directly from online resources or databases.

using Spire.Doc;
using Spire.Doc.Documents;

namespace InsertImageFromByteArray
{
    class Program
    {
        static async System.Threading.Tasks.Task Main(string[] args)
        {
            // URL of the image
            string imageUrl = "https://example.com/image.png";

            // Download the image
            byte[] imageBytes;
            using (HttpClient client = new HttpClient())
            {
                imageBytes = await client.GetByteArrayAsync(imageUrl);
            }

            // Create a Document object
            Document document = new Document();

            // Add a section
            Section section = document.AddSection();

            // Add a paragraph
            Paragraph paragraph = section.AddParagraph();

            // Append a picture from the byte array
            using (MemoryStream stream = new MemoryStream(imageBytes))
            {
                paragraph.AppendPicture(stream);
            }

            // Save the document
            document.SaveToFile("output.docx", FileFormat.Docx);

            // Dispose resources
            document.Dispose();
        }
    }
}

Further Customize the Image

Professional documents often demand precise image formatting. Spire.Doc offers extensive controls through the DocPicture class, enabling users to manipulate images effectively.

Key features include resizing to fit layouts, rotating for optimal orientation, and text wrapping options that allow text to flow seamlessly around images. Additionally, users can specify spacing and alignment to position images accurately relative to surrounding content.

// Append an image from disk
DocPicture picture = paragraph.AppendPicture("C:\\Users\\Administrator\\Desktop\\MyPic.png");

// Resize the image to 70%
picture.SetScale(70f);

// Rotate the image 10 degrees counterclockwise
picture.Rotation = -10;

// Specify top and bottom distance to 3 units
picture.DistanceTop = picture.DistanceBottom = 3;

// Set the text wrapping style around the image
picture.TextWrappingStyle = TextWrappingStyle.TopAndBottom;

// Center align the paragraph containing the image
paragraph.Format.HorizontalAlignment = HorizontalAlignment.Center;

Conclusion

Using Spire.Doc for .NET simplifies the process of inserting and customizing images in Word documents. Whether pulling images from local storage or online sources, the library provides flexible options to enhance document presentation.

Get a Free License

To fully experience the capabilities of Spire.Doc for .NET without any evaluation limitations, you can request a free 30-day trial license.

C#: Edit Word Documents

2024-08-08 06:35:00 Written by Administrator

Editing a Word document is necessary when you want to improve readability, correct errors, refine formatting, maintain consistency, adapt content, facilitate collaboration, and optimize the document for any other purposes. Programmatically editing a Word document using C# can be a powerful approach to automate document processing and manipulation tasks.

In this article, you will learn how to edit a Word document using C# and the Spire.Doc for .NET library.

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

Modify Text in a Word Document in C#

Spire.Doc allows you to programmatically access specific sections and paragraphs in Word documents. To retrieve a particular section, use the Document.Sections[index] property. Then, to get a particular paragraph within that section, leverage the Section.Paragraphs[index] property. Finally, you can update the text content of the paragraph using the Paragraph.Text property.

The steps to modify text in a Word document using C# are as follows:

  • Create a Document object.
  • Load a Word file from the given file path.
  • Get a specific section through Document.Sections[index] property.
  • Get a specific paragraph through Section.Paragraphs[index] property.
  • Reset the text of the paragraph through Paragraph.Text property.
  • Save the updated document to a different Word file.
  • C#
using Spire.Doc;
using Spire.Doc.Documents;

namespace ModifyText
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a new document object
            Document document = new Document();

            // Load an existing Word file
            document.LoadFromFile("C:\\Users\\Administrator\\Desktop\\input.docx");

            // Get a specific section
            Section section = document.Sections[0];

            // Get a specific paragraph
            Paragraph paragraph = section.Paragraphs[0];

            // Modify the text of the paragraph 
            paragraph.Text = "Updated Title";

            // Save the document to a different Word file
            document.SaveToFile("ModifyText.docx", FileFormat.Docx);

            // Dispose resource
            document.Dispose();
        }
    }
}

C#: Edit Word Documents

Change Formatting of Text in a Word Document in C#

To change the text formatting within a paragraph, first obtain the paragraph object, then iterate through its child objects to locate the individual text ranges. For each text range, you can reset the formatting using the CharacterFormat property of the TextRange.

The steps to change text formatting in a Word document are as follows:

  • Create a Document object.
  • Load a Word file from the given file path.
  • Get a specific section through Document.Sections[index] property.
  • Get a specific paragraph through Section.Paragraphs[index] property.
  • Iterate through the child objects in the paragraph.
    • Determine if a child object is a text range.
    • Get a specific text range.
    • Reset the text formatting through TextRange.CharacterFormat property.
  • Save the updated document to a different Word file.
  • C#
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using System.Drawing;

namespace ChangeTextFont
{
    class Program
    {
        static void Main(string[] args)
        {

            // Create a new document object
            Document document = new Document();

            // Load an existing Word file
            document.LoadFromFile("C:\\Users\\Administrator\\Desktop\\input.docx");

            // Get a specific section
            Section section = document.Sections[0];

            // Get a specific paragraph
            Paragraph paragraph = section.Paragraphs[2];

            // Iterate through the child objects in the paragraph
            for (int i = 0; i < paragraph.ChildObjects.Count; i++)
            {

                // Determine if a child object is text range
                if (paragraph.ChildObjects[i] is TextRange)
                {
                    // Get a specific text range
                    TextRange textRange = (TextRange)paragraph.ChildObjects[i];

                    // Reset font name for it
                    textRange.CharacterFormat.FontName = "Corbel Light";

                    // Reset font size for it
                    textRange.CharacterFormat.FontSize = 11;

                    // Reset text color for it
                    textRange.CharacterFormat.TextColor = Color.Blue;

                    // Apply italic to the text range 
                    textRange.CharacterFormat.Italic = true;
                }
            }

            // Save the document to a different Word file
            document.SaveToFile("ChangeFont.docx", FileFormat.Docx);

            // Dispose resource
            document.Dispose();
        }
    }
}

C#: Edit Word Documents

Add New Elements to a Word Document in C#

In addition to modifying the existing content in a Word document, you can also insert various types of new elements, such as text, images, tables, lists, and charts. As most elements are paragraph-based, you have the flexibility to add a new paragraph at the end of the document or insert it mid-document. You can then populate this new paragraph with the desired content, whether that's plain text, images, or other elements.

Below are the steps to add new elements (text and images) to a Word document using C#:

  • Create a Document object.
  • Load a Word file from the given file path.
  • Get a specific section through Document.Sections[index] property.
  • Add a paragraph to the section using Section.AddParagraph() method.
  • Add text to the paragraph using Paragraph.AppendText() method.
  • Add an image to the paragraph using Paragraph.AppendPicture() method.
  • Save the updated document to a different Word file.
  • C#
using Spire.Doc;
using Spire.Doc.Documents;

namespace AddNewElementsToWord
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a new document object
            Document document = new Document();

            // Load an existing Word file
            document.LoadFromFile("C:\\Users\\Administrator\\Desktop\\input.docx");

            // Get the last section
            Section lastSection = document.LastSection;

            // Add a paragraph to the section
            Paragraph paragraph = lastSection.AddParagraph();

            // Add text to the paragraph
            paragraph.AppendText("This text and the image shown below are added programmatically using C# and Spire.Doc for .NET.");

            // Add an image to the paragraph
            paragraph.AppendPicture("C:\\Users\\Administrator\\Desktop\\logo.png");

            // Create a paragraph style
            ParagraphStyle style = new ParagraphStyle(document);
            style.Name = "FontStyle";
            style.CharacterFormat.FontName = "Times New Roman";
            style.CharacterFormat.FontSize = 12;
            document.Styles.Add(style);

            // Apply the style to the paragraph
            paragraph.ApplyStyle(style.Name);

            // Save the document to a different Word file
            document.SaveToFile("AddNewElements.docx", FileFormat.Docx);

            // Dispose resource
            document.Dispose();
        }
    }
}

C#: Edit Word Documents

Remove Paragraphs from a Word Document in C#

With the Spire.Doc library, you can perform a variety of document operations, including updating existing content, adding new elements, as well as removing elements from a Word document. For example, to remove a paragraph from the document, you can use the Section.Paragraphs.RemoveAt() method.

The following are the steps to remove paragraphs from a Word document using C#:

  • Create a Document object.
  • Load a Word file from the given file path.
  • Get a specific section through Document.Sections[index] property.
  • Remove a specific paragraph from the section using Section.Paragraphs.RemoveAt() method.
  • Save the updated document to a different Word file.
  • C#
using Spire.Doc;

namespace RemoveParagraphs
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a new document object
            Document document = new Document();

            // Load an existing Word file
            document.LoadFromFile("C:\\Users\\Administrator\\Desktop\\input.docx");

            // Get a specific section
            Section section = document.Sections[0];

            // Remove a specific paragraph
            section.Paragraphs.RemoveAt(0);

            // Save the document to a different Word file
            document.SaveToFile("RemoveParagraph.docx", FileFormat.Docx);

            // Dispose resource
            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.

page 321