Read page headers and footers from Word.Range - VSTO Word Interop C #

I have an object Range, and I want to use it to extract information from the page on which it is located Range. The information is in the headers and footers inside the table, I want to read the text from the table.

I tried: word.Sections[1].Headers[WdHeaderFooterIndex.wdHeaderFooterPrimary].Shapes.Range(ref pageNumber).TextFrame.TextRange.Text;

Where the word Rangeand pageNumberis the page number in which this range is located. The problem is that I can’t get the real page number! using word.get_information(WdInformation.wdActiveEndPageNumber)returns the wrong page number!

+3
source share
1 answer

I found the answer that interests any1:

int i = (int)range.get_Information(WdInformation.wdActiveEndPageNumber) % 2;
WdHeaderFooterIndex index;
if (i == 0 && range.Sections[1].PageSetup.OddAndEvenPagesHeaderFooter == 1)
    index = WdHeaderFooterIndex.wdHeaderFooterEvenPages;
else
    index = WdHeaderFooterIndex.wdHeaderFooterPrimary;

Range sRange = range.Sections[1].Range;
object direction = Word.WdCollapseDirection.wdCollapseStart;
sRange.Collapse(ref direction);
if (range.get_Information(WdInformation.wdActiveEndPageNumber) == sRange.get_Information(WdInformation.wdActiveEndPageNumber)
    && range.Sections[1].PageSetup.DifferentFirstPageHeaderFooter == 1)
    index = WdHeaderFooterIndex.wdHeaderFooterFirstPage;

object rangeIndex = 1;
Range headerRange = range.Sections[1].Headers[index].Range.ShapeRange.TextFrame.TextRange;

string profession = headerRange.Tables[1].Cell(4, 1).Range.Text;
string manPower = headerRange.Tables[1].Cell(4, 2).Range.Text;
string registration = headerRange.Tables[1].Cell(4, 3).Range.Text;
string taggingListNum = headerRange.Tables[1].Cell(4, 4).Range.Text;
+6
source

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


All Articles