MS Word page break inserting in wrong place
I am creating a MS Word document entirely through C# in VS 2008. I am trying to insert a page break, and when the page break is inserted, instead of inserting it and adding a new page at the bottom, it is inserting a break and adding a page at the top. This results in the first page being the last page.
Here is the code for inserting the page break:
start = 0;
end = 0;
Word.Range rngDoc = Range(ref start, ref end);
rngDoc.Collapse(ref CollapseEnd);
rngDoc.InsertBreak(ref pageBreak);
rngDoc.Collapse(ref CollapseEnd);
Also, each page is consumed 开发者_开发技巧by a table, if this helps with the diagnostics
InsertBreak
never inserts after the selection. Note the MSDN remarks:
When you insert a page or column break, the selection is replaced by the break. If you don't want to replace the selection, use the
Collapse
method before using theInsertBreak
method. When you insert a section break, the break is inserted immediately preceding theSelection
object.
(My emphasis.) To get a break at the end of the page, I think you'll have to select nothing (as you are here) at the end of the document.
I can't recall whether the Document
has its own range. Can you just get an all-encompassing range from myDoc.Characters
?
If not, the first thing I would try is
start = int.MaxValue;
end = int.MaxValue;
If that doesn't work, you might resort to ComputeStatistics()
. Something like this:
WdStatistic stats = WdStatistic.wdStatisticCharacters;
var chars = myDoc.ComputeStatistics(stats, false);
And then create your range from that value. Wish I could help more, but it's been a while for me. Good luck!
You need to set the rngDoc
to insert at the end of ActiveDocument.Range
. Here's some VBA that would be easy to port to C# that does this.
Sub InsertNewPageAtEndofDoc()
Dim rng As Range
Dim adRange As Range
Set adRange = ActiveDocument.Range
Set rng = ActiveDocument.Range(adRange.Start, adRange.End)
rng.Collapse (wdCollapseEnd)
rng.InsertBreak (wdPageBreak)
rng.Collapse (wdCollapseEnd)
End Sub
I used Todds approach but in vb.net:
Private Sub InsertNewPageAtEndofDoc(app As Word.Application)
Dim rng As Word.Range
Dim adRange As Word.Range
adRange = app.ActiveDocument.Range
rng = app.ActiveDocument.Range(adRange.Start, adRange.End)
rng.Collapse(Word.WdCollapseDirection.wdCollapseEnd)
rng.InsertBreak(Word.WdBreakType.wdPageBreak)
rng.Collapse(Word.WdCollapseDirection.wdCollapseEnd)
End Sub
I'm not an expert at this so this is just a guess, it looks a bit strange though that you're selecting a range from 0 to 0 and then collapsing that. A range from 0 to 0 sounds like it'll give you the very start of the document, I'd guess that you need to select the last bit of the document instead but not sure how to do that.
精彩评论