artifex_somnia
artifex_somnia

Reputation: 438

Retrieving page number by contained paragraph

I'm having difficulty fetching page numbers in according to the paragraphs on them. My code is the following. para_list stores the paragraphs in which the phrase i'm searching for is found. I then attempt to select the range and then retrieve the page number..however all I receive is the same page number repeatedly. Can someone suggest another method or reveal what I'm doing wrong. Thanks

for para in doc.Paragraphs:
    count=count+1
    if phrase in para.Range.Text:

        para.Range.Select
        para_list.append(count)
        p_list.append(doc.ActiveWindow.Selection.Information(constants.wdActiveEndAdjustedPageNumber))

Upvotes: 0

Views: 202

Answers (2)

Oliver
Oliver

Reputation: 29483

Seems to me like using Range.Information[constants.wdActiveEndAdjustedPageNumber] is the right way (see for example the second answer in How do I find the page number for a Word Paragraph). However I'm not sure why you are operating on the selection, rather than the paragraph range itself. I would guess (can't try here) that the following should work:

for count, para in enumerate(doc.Paragraphs):
    if phrase in para.Range.Text:
        pageNum = para.Range.Information(constants.wdActiveEndAdjustedPageNumber)
        print 'page for para #%s is %s' % (count, pageNum)

Stylistic note: para_list and p_list? The names should more clearly identify the purpose of each container.

Upvotes: 2

artifex_somnia
artifex_somnia

Reputation: 438

As a hack you can use

range_obj =doc.ActiveWindow.Selection.GoTo(constants.wdGoToPage,constants.wdGoToNext,1 )
range_obj2 =doc.ActiveWindow.Selection.GoTo(constants.wdGoToPage,constants.wdGoToNext,1 )

char_index1= range_obj.start #will give you the character index for end of one page
char_index2 = range_obj2.start # character index for next page

#Compare with the paragraph index. The min positive difference tells you the page the paragraph is on

position= doc.Paragraphs(index).start

Upvotes: 0

Related Questions