Word Automation: Detect if page break is necessary?

前提是你 提交于 2019-12-05 00:27:01

问题


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.


回答1:


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!




回答2:


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.



来源:https://stackoverflow.com/questions/825254/word-automation-detect-if-page-break-is-necessary

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!