page 249

This article presents how to create a Windows Forms Application to open a Word file and convert it to PDF format using Spire.DocViewer. In fact, conversion from Word to HTML, RTF, DOC, DOCX are also supported with this DocViewer control. You can try almost the same way demonstrated in the following section to convert Word to any other format.

First of all, download Spire.DocViewer, add DocViewer Control to VS Toolbox.

Save Word File to PDF using Spire.DocViewer

Then create a Windows Forms application, design your Form1 as below.

  • Add 'Open' button to open a file from existing Word document.
  • Add 'Close' button to shut down the open file.
  • Add 'ToPDF' button to save Word file as PDF format.
  • Drag 'DocDocumentViewer Control' into Form1, which is used to display Word document.

Save Word File to PDF using Spire.DocViewer

Code Snippet:

Step 1: Initialize components in Form1.

       public Form1()
       {
          InitializeComponent(); 
       }

Step 2: Create an OpenFileDialog to select the correct file type that we want to load, otherwise error message 'Cannot detect current file type' will appear.

       private void bntOpen_Click(object sender, EventArgs e)
        {
            //Open a doc document          
            OpenFileDialog dialog = new OpenFileDialog();
            dialog.Filter = "Word97-2003 files(*.doc)|*.doc|Word2007-2010 files (*.docx)|*.docx|All files (*.*)|*.*";
            dialog.Title = "Select a DOC file";
            dialog.Multiselect = false;
            dialog.InitialDirectory = System.IO.Path.GetFullPath(@"..\..\..\..\..\..\Data");

            DialogResult result = dialog.ShowDialog();

            if (result == DialogResult.OK)
            {
                try
                {
                    this.docDocumentViewer1.LoadFromFile(dialog.FileName);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

Step 3: In the 'ToPDF' button click event, create a SaveFileDialog, set filter as PDF type, then call DocDocumentViewer.SaveAs() method to save Word as PDF with customized file name.

       private void btnSaveToPdf_Click(object sender, EventArgs e)
        {
            SaveFileDialog savefile = new SaveFileDialog();
            savefile.Filter = "Pdf Document(*.pdf)|*.pdf";
            savefile.Title = "Save";

            DialogResult result = savefile.ShowDialog();
            if (result == DialogResult.OK)
            {
                try
                {
                    //Save PDF documetns
                    this.docDocumentViewer1.SaveAs(savefile.FileName);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

Step 4: Close the open file.

        private void btnClose_Click(object sender, EventArgs e)
        {
            //Close current doc document.
            this.docDocumentViewer1.CloseDocument();
        }

After debugging the code, I opened a sample Word file. The save dialog box will pop up by clicking 'ToPDF' button.

Save Word File to PDF using Spire.DocViewer

This article presents how to create a Windows Forms application to open and close your Word files using Spire.DocViewer component. Detailed steps would be as follows:

First of all, download Spire.DocViewer, add DocViewer Control to VS Toolbox.

How to Open and Close Word Files using Spire.DocViewer

Then create a Windows Forms application, design your Form1 as below.

  • Add 'Open from file' button to open a file from existing Word document.
  • Add 'Open from stream' button to load a Word file from steam.
  • Add 'Close' button to shut down the open file.
  • Drag 'DocDocumentViewer Control' into Form1, which is used to display Word document.

How to Open and Close Word Files using Spire.DocViewer

Code Snippet:

Step 1: Initialize components in Form1.

        System.IO.FileStream stream;
        public Form1()
        {
            InitializeComponent();
          
        }

Step 2: Create an OpenFileDialog to select the correct file type that we want to load, otherwise error message 'Cannot detect current file type' will occur.

private void btnOpen_Click(object sender, EventArgs e)
        {
            //open a DOC document
            OpenFileDialog dialog = new OpenFileDialog();
            dialog.Filter = "Word97-2003 files(*.doc)|*.doc|Word2007-2010 files (*.docx)|*.docx|All files (*.*)|*.*";
            dialog.Title = "Select a DOC file";
            dialog.Multiselect = false;
            dialog.InitialDirectory = System.IO.Path.GetFullPath(@"..\..\..\..\..\..\Data");

            DialogResult result = dialog.ShowDialog();

            if (result == DialogResult.OK)
            {
                try
                {
                    //Load DOC document from file.
                    this.docDocumentViewer1.LoadFromFile(dialog.FileName);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

Step 3: This button code enables users to open Word files from a stream in Xml or Microsoft Word format.

        private void btnOpenStream_Click(object sender, EventArgs e)
        {
            //open a doc document
            OpenFileDialog dialog = new OpenFileDialog();
            dialog.Filter = "Word97-2003 files(*.doc)|*.doc|Word2007-2010 files (*.docx)|*.docx|All files (*.*)|*.*";
            dialog.Title = "Select a DOC file";
            dialog.Multiselect = false;
            dialog.InitialDirectory = System.IO.Path.GetFullPath(@"..\..\..\..\..\..\Data");
            
            DialogResult result = dialog.ShowDialog();

            if (result == DialogResult.OK)
            {
                try
                {
                    string docFile = dialog.FileName;
                    stream = new System.IO.FileStream(docFile, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read);
                    if (stream != null)
                    {
                        //Load doc document from stream.
                        this.docDocumentViewer1.LoadFromStream(stream, Spire.Doc.FileFormat.Auto);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

Step 4: Close the open file.

        private void btnClose_Click(object sender, EventArgs e)
        {
            //Close current doc document.
            this.docDocumentViewer1.CloseDocument();
        }

After running the code, I opened a test file with this Windows application. Here is the screenshot of effect:

How to Open and Close Word Files using Spire.DocViewer

C#: Add Page Numbers to a Word Document

2024-04-26 02:22:00 Written by Koohji

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.

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();
        }
    }
}

C#: Add Page Numbers to a Word Document

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();
        }
    }
}

C#: Add Page Numbers to a Word Document

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();
        }
    }
}

C#: Add Page Numbers to a Word Document

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 249