Click here to Skip to main content
Email Password   helpLost your password?

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:

  1. Create an object of Word Application.
  2. Open the required Word document using the open() function of Documents collection of Word document. This function returns the Word.Document object.
  3. 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 
      { 
            /// <SUMMARY> 

            /// The main entry point for the application. 

            /// </SUMMARY> 

            [STAThread] 
            static void Main(string[] args) 
            { 
                Word.ApplicationClass WordApp = new Word.ApplicationClass(); 

                // give any file name of your choice. 

                object fileName = "D:\\abc\\oop1.doc"; 
                object readOnly = false; 
                object isVisible = true;

                //  the way to handle parameters you don't care about in .NET 

                object missing = System.Reflection.Missing.Value; 

                //   Make word visible, so you can see what's happening 

                //WordApp.Visible = true; 

                //   Open the document that was chosen by the dialog 

                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(); 
            } 
      } 
} 
You must Sign In to use this message board.
 
 
Per page   
 FirstPrevNext
GeneralSome Example Application
Epstone
7:24 16 Feb '10  
I've created an example application for the code. Easy to use in office work.

Please make a copy of your Word files and close all Word instances before using.
You can download it here: [Link]
GeneralComplete document statistics, including image.. Possible?
kartika9
16:15 26 Aug '09  
Hi Shelly,
thanks for sharing this tutorial.

Extending this bit further, would that be possible to count how many images inside a particular document?

I was in the middle of a project which requires to compare two documents which in different languages. And, the expected outcome is generating a report, how different those documents based on the statistics, for this early stage.
I managed to compute: Paragraphs, Words, Sentences, Styles, Tables and Pages -> which were easily obtained from the object.

Have any idea?

Thank you very much Smile
GeneralMS Office app is required in the targate machice
Md. Marufuzzaman
21:32 26 Jun '09  
Hi..
To implemtnts and deploy it as COM+ app, is the ms office need to install in the targete machine.

Md. Marufuzzaman

GeneralRe: MS Office app is required in the targate machice
PRMan!!!
13:13 9 Dec '09  
If you trust the summary information to be correct (it is updated each time Word saves the document using the editor's printer settings, but maybe not for OpenOffice, Abiword, etc.), you could just open the file and do a Regex search for "nofpages(\d+)":

int pages = -1;
string word = File.ReadAllText(pathtodoc);
Match m = Regex.Match(@"noofpages(\d+)", word);
if (m.Success)
{
int.TryParse(m.Groups[1].Value, out pages);
}

Of course, this also only works for documents that aren't huge, but most Word files are relatively small (10s of KB). Even the big ones are usually in the 10s of MB, which is nothing on 1-4GB RAM machines.

This also works for RTF files, BTW.
GeneralRe: MS Office app is required in the targate machice
Md. Marufuzzaman
2:15 11 Dec '09  
Thanks...Smile

Thanks
Md. Marufuzzaman

Don't forget to click [Vote] / [Good Answer] on the post(s) that helped you.
I will not say I have failed 1000 times; I will say that I have discovered 1000 ways that can cause failure – Thomas Edison.

GeneralClever
Derek Bartram
9:00 26 Apr '08  
I'm not sure this justified an article personally, however it's kinda clever, I didn't know you could do that!
GeneralHow can I access each page of word document
KKGaurav
2:45 17 Sep '07  
Maam I want to save each page in Word.Page type object so that I can play only with a single page of a document.My requirement is to save each page of a document as a html page.But still I am only able to whole document as a html document.So please suggest to access one by one page.




KrishanSleepy

KK Gaurav
App Developer
Religare Securities Ltd Delhi

GeneralWriting Data to Word Document
srujana_m
3:13 24 Jul '07  
Hi,
I have some code that generates an xml file and word document parallely. I have to read the xml file and write that data to word document. Writing to word document is based on the xml nodes that is data in first node should go to the first page in the doc file similarly second node text to second page so on. So can anyone help me out

Thnx in advance.

Srujana
QuestionPerformance issue
Lokanatha Reddy
2:09 3 Apr '07  
Hi,
I tried to read all paragraphs from sample doc. It took 6 mins for 30 pages. Is there any other alternate approach to do the same? What about VBA and macros?

Regards,
Loka
QuestionGet Header style
Lokanatha Reddy
3:38 27 Mar '07  
Hi,
How to get heading style? I want to read paragraphs and table contents based on heading style.

Loka
GeneralRead content From Multiple word document Files
Satish_CHVS
3:24 1 Sep '06  
Hi..
i am selcting multiple number of Word document files.
i want read the data from that files,i.e.copy the content from that
and edit in a single document without merging.(concatenation)
is it possible by using asp.net with C#.

satish
GeneralReading MSG-files with C#?
Wolfram Menzel
4:13 9 Mar '05  
Does anybody have an example where IStorage is used in C#? I have to write a program, which has to read data from MSG-files created by Outlook.
I would be very glad for any answer to "wolfram.menzel@siemens.com".
Thanks a lot.

Wolfram Menzel
Siemens AG, Germany
I&S GIO IP 2
Tel. +49(0)9131-731897
Handy: 0173 39 275 61
GeneralNeed save a Word document
Anonymous
8:11 1 Sep '04  
hi, i need to save a word document, but i want to force the name of the document and the directory, i don´t want the dialog box from the word for save the file.
thank's
Andres
(Argentina)
GeneralHow to count the number of words in the Document
ganekun
22:35 30 Jul '04  
Hi all.

I am studying on how to access MS Word Documents.
I still can't find a way to count the number of words in a document file.
Any help or hint I can get?
GeneralRe: How to count the number of words in the Document
georgi nastev
7:01 23 Oct '06  
You can count the words in the same way as this counting the pages, but instead of this line:
Word.WdStatistic stats = Word.WdStatistic.wdStatisticPages

you can use:
Word.WdStatistic stats = Word.WdStatistic.wdStatisticWords
GeneralWord Doc tags
kanch eramudu
8:56 18 Aug '03  
D'Oh!
I am reading a word document and write it to another Word doc. I need to do some editing to the paragraphs before writing it back. In order to do that, i have to find the style of the word. For example if it is a "heading 1" or "Title". etc.
I tried to use the property "style", but it doesn't work. Is there any other method i can use?

Kanch
GeneralOffice XP
Ray Cassick
13:08 30 Apr '03  
I tested this out with Office XP and, after adding the COM reference to the Word object library, was getting the following error:

No overload for method 'Open' takes '12' arguments
After some investigation of the .Open method This is the change I needed to make to the code to get the example to work:
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, ref missing,
ref missing, ref missing);
I am not sure if this is ONLY for Office XP users because I don't have another version handy to test it on.




Paul Watson wrote: "At the end of the day it is what you produce that counts, not how many doctorates you have on the wall." George Carlin wrote: "Don't sweat the petty things, and don't pet the sweaty things." Jörgen Sigvardsson wrote: If the physicists find a universal theory describing the laws of universe, I'm sure the a**hole constant will be an integral part of that theory.

GeneralRe: Office XP
yuronline
7:48 26 Aug '07  
add 4 more ref missing in the argument list.
GeneralMissing things?
Ray Cassick
10:46 30 Apr '03  
1 - No sample project?

2 - Code will not build as it sits because of a missing reference to the Microsoft Word object library.

3 - Event after I added a ref to the Word object libray I get an error:

No overload for method 'Open' takes '12' arguments

I have not looked into it too closely (heading into a meeting right now) but....


Paul Watson wrote: "At the end of the day it is what you produce that counts, not how many doctorates you have on the wall." George Carlin wrote: "Don't sweat the petty things, and don't pet the sweaty things." Jörgen Sigvardsson wrote: If the physicists find a universal theory describing the laws of universe, I'm sure the a**hole constant will be an integral part of that theory.

GeneralRe: Missing things?
MisterG
5:53 1 Jul '04  
Try this :

Word.Document aDoc = WordApp.Documents.Open2000(ref fileName,
ref missing,ref readOnly, ref missing,
ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing,
ref missing, ref isVisible);


Last Updated 30 Apr 2003 | Advertise | Privacy | Terms of Use | Copyright © CodeProject, 1999-2010