C#/VB.NET: Set Page Margins for Word Documents

Page margins are the distance from the page edges to the content area. They are helpful in making a document look neat and professional. When generating a document in Microsoft Word, you may need to set page margins to make the document look better. In this article, we will demonstrate how to set page margins for Word documents in C# and VB.NET 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

Set Page Margins in Word in C# and VB.NET

The following are the steps to set page margins in Word:

  • Initialize an instance of Document class.
  • Load a Word document using Document.LoadFromFile() method.
  • Get the desired section through Document.Sections[sectionIndex] property.
  • Set the top, bottom, left and right margins for the pages in the section through Section.PageSetup.Margins.Top, Section.PageSetup.Margins.Bottom, Section.PageSetup.Margins.Left, Section.PageSetup.Margins.Right properties.
  • Save the result document using Document.SaveToFile() method.
  • C#
  • VB.NET
using Spire.Doc;

namespace PageMargins
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a Document instance
            Document document = new Document();
            //Load a Word document
            document.LoadFromFile(@"Sample.docx");

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

            //Set top, bottom, left and right page margins for the section
            section.PageSetup.Margins.Top = 17.9f;
            section.PageSetup.Margins.Bottom = 17.9f;
            section.PageSetup.Margins.Left = 17.9f;
            section.PageSetup.Margins.Right = 17.9f;

            //Save the result document
            document.SaveToFile("SetMargins.docx", FileFormat.Docx2013);
        }
    }
}

C#/VB.NET: Set Page Margins for 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.