Introduction
This article explains how to count the pages in MS Word document programmatically using C#.
Using the code
To count the pages in MSWord document, we need to follow following steps:
- Create an object of Word Application.
- Open the required Word document using the open() function of Documents collection of Word document. This function returns the Word.Document object.
- Cal the
ComputeStatistics fumction on Word.Document object passing it an enum WdStatistic with value equal to wdStatisticPages. This function will return the number of pages in the opened word document.
Here is the Code:
using System;
namespace DocPageCounter
{
class PageCounter
{
[STAThread]
static void Main(string[] args)
{
Word.ApplicationClass WordApp = new Word.ApplicationClass();
object fileName = "D:\\abc\\oop1.doc";
object readOnly = false;
object isVisible = true;
object missing = System.Reflection.Missing.Value;
Word.Document aDoc = WordApp.Documents.Open(ref fileName,
ref missing,ref readOnly, ref missing,
ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing,
ref missing, ref isVisible);
Word.WdStatistic stat = Word.WdStatistic.wdStatisticPages ;
int num = aDoc.ComputeStatistics(stat,ref missing);
System.Console.WriteLine ("The number of pages in doc is {0}",
num);
System.Console.ReadLine();
}
}
}