How to Set Page Size of Word Document in C#

In Microsoft Word, the default page size is 8.5x11 inch letter. Apart from this, MS Word also provides some other predefined page sizes such as Legal (5.4x14), A4 (8.27x11.69), A5 (5.83x8.27) for users to easily change the page size to meet different requirements. Additionally, if your page size is not in the list, you can select Custom size from Page Setup to customize the page size with the specified width and height.

In fact, Spire.Doc has provided similar ways for programmers to set the Word page size. This article will present how to choose a defined page size or how to set custom size for your Word document using Spire.Doc in C#.

Code Snippet:

Step 1: Create a Word document with a blank section.

Document doc = new Document();
Section section = doc.AddSection();

Step 2: Set page size as A4. In the PageSize class, there are plenty of defined page sizes preconfigured for you.

section.PageSetup.PageSize = PageSize.A4;

However, if you would like to set the page with custom size, replace the above code with following code snippet.

section.PageSetup.PageSize = new System.Drawing.SizeF(500, 800);
section.PageSetup.Orientation = PageOrientation.Portrait;

Step 3: Append some text to the section.

Paragraph Para = section.AddParagraph();
Para.AppendText("Spire.Doc for .NET, a professional .NET Word component, "
+ "enables developers to perform a large range of tasks on Word document (from Version Word97-2003 to Word 2010) "
+ "for .NET in C# and VB.NET. ");

Step 4: Save the file and start to view.

doc.SaveToFile("result.docx", FileFormat.Docx);
System.Diagnostics.Process.Start("result.docx");

Output:

1) Choose a defined page size.

How to Set Page Size of Word Document in C#

2) Customize the size of Word document.

How to Set Page Size of Word Document in C#

Full Code:

using System.Drawing;
using Spire.Doc;
using Spire.Doc.Documents;

namespace CustomPageSize
{
    class Program
    {
        static void Main(string[] args)
        {
            Document doc = new Document();
            Section section = doc.AddSection();
            
            section.PageSetup.PageSize = PageSize.A4;
            //section.PageSetup.PageSize = new System.Drawing.SizeF(550, 800);
            //section.PageSetup.Orientation = PageOrientation.Portrait;

            Paragraph Para = section.AddParagraph();
            Para.AppendText("Spire.Doc for .NET, a professional .NET Word component, "
            + "enables developers to perform a large range of tasks on Word document (from Version Word97-2003 to Word 2010) "
            + "for .NET in C# and VB.NET. ");
           
            doc.SaveToFile("result.docx", FileFormat.Docx);
            System.Diagnostics.Process.Start("result.docx");
        }
    }
}