views:

199

answers:

2

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

A: 

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.

ho1
Yeah that is what I am guessing, but since the document page has a table consuming the entire area, it is causing errors with the next page. I am not sure what "end" to get.
mattgcon
A: 

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 the InsertBreak method. When you insert a section break, the break is inserted immediately preceding the Selection 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!

ladenedge
I am going to take your idea of character stats and see what I can do. I have an idea but I will need to make changes to my code extensively to make it work. I am going to use the Document.Characters.First.Start and Document.Characters.Last.End ranges and see if I can do something with those.
mattgcon
the character idea worked and it is now inserting after the current page than you
mattgcon