How to get page number?

I have this code:

Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.Application(); object nullobj = System.Reflection.Missing.Value; object file = openFileDialog1.FileName; Microsoft.Office.Interop.Word.Document doc = app.Documents.Open( ref file, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj); doc.ActiveWindow.Selection.WholeStory(); doc.ActiveWindow.Selection.Copy(); IDataObject data = Clipboard.GetDataObject(); string text = data.GetData(DataFormats.Text).ToString(); textBox2.Text = text; doc.Close(ref nullobj, ref nullobj, ref nullobj); app.Quit(ref nullobj, ref nullobj, ref nullobj); 

But it does not return the page number. How can I get the page number?

+4
source share
3 answers

Take a look at this example:

http://www.c-sharpcorner.com/UploadFile/amrish_deep/WordAutomation05102007223934PM/WordAutomation.aspx

In particular, see Word.WdFieldType.wdFieldPage and Word.WdFieldType.wdFieldNumPages .

+1
source

I would say that this is the best solution

 Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.Application(); object nullobj = System.Reflection.Missing.Value; object file = openFileDialog1.FileName; Microsoft.Office.Interop.Word.Document doc = app.Documents.Open( ref file, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj); doc.ActiveWindow.Selection.WholeStory(); doc.ActiveWindow.Selection.Copy(); IDataObject data = Clipboard.GetDataObject(); // get number of pages Microsoft.Office.Interop.Word.WdStatistic stat = Microsoft.Office.Interop.Word.WdStatistic.wdStatisticPages; int pages = doc.ComputeStatistics(stat, Type.Missing); string text = data.GetData(DataFormats.Text).ToString(); textBox2.Text = text; doc.Close(ref nullobj, ref nullobj, ref nullobj); app.Quit(ref nullobj, ref nullobj, ref nullobj); 
+6
source

For me, the ComputeStatistics function would give me a larger number than the actual number of pages so that this would not work for me.

I used range.get_Information ()

 var range = doc.Range().GoTo(WdGoToItem.wdGoToPage, WdGoToDirection.wdGoToLast); var numPages = range.get_Information(WdInformation.wdActiveEndPageNumber); 

The first line gets the range on the last page of the document. The second line gets the page with the range.

0
source

Source: https://habr.com/ru/post/1308526/


All Articles