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.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With