views:

730

answers:

2

Hi,

I am working on a project in C# that will produce a Word document using the Word Automation API.

I would like to insert page breaks at specific points in the generated document and I am currently doing this successfully with the following code:

// Generate page break
object pageBreak = WdBreakType.wdPageBreak;
wordApp.Selection.InsertBreak(ref pageBreak);

However, if the document has naturally wrapped onto the next page anyway after running out of room on the previous page then I don't really want to be generating a page break or else I will end up with a blank page.

What I would really like is the ability to find out exactly where the cursor is and if it is on the first line and column of the current page then I can safely assume that it is not necessary to insert a page break.

Is there a way to access the position of the cursor? Or another solution that would do the same thing? It seems like a simple requirement so I apologize in advance if I have missed the obvious.

Thanks, Alan

+1  A: 

Assuming that you are programmatically building the document in a way that would cause wordApp.Selection to properly reflect your actual (and relevant) position in the document, you can determine its line and column on its starting page using its Information property and the following two WdInformation enums (shown here as VBA; not sure what the .NET PIA syntax is offhand):

line = wordApp.Selection.Information(wdFirstCharacterLineNumber)
col = wordApp.Selection.Information(wdFirstCharacterColumnNumber)

These values correspond to the Ln and Col values seen in Word's status bar. If they are both equal to 1, then you are in the first position of the page on which the Selection begins.

Good luck!

ewbi
Thank you very much for your help. This is exactly what I wanted to do.
Alan Spark
A: 

You could try setting property on the paragraph that causes it to have a page break before it. I don't if Word Automation API allows it to be set, but it seems exactly what you need.

ya23