How to insert Page break when creating MS Word document

25,904

Solution 1

Here is an example of writing some text to the word doc then adding a page break. Then writing the rest to the text to the document. In order to get a better answer you may need to rewrite your question as it is unclear when you want to insert a break and how you are writing the information to the document. I am assuming a lot which is never good.

using Word = Microsoft.Office.interop.Word; 

//create a word app
Word._Application  wordApp = new Word.Application();
//add a page
Word.Document doc = wordApp.Documents.Add(Missing.Value, Missing.Value, Missing.Value, Missing.Value);
//show word
wordApp.Visible = true;
//write some tex
doc.Content.Text = "This is some content for the word document.\nI am going to want to place a page break HERE ";
//inster a page break after the last word
doc.Words.Last.InsertBreak(Word.WdBreakType.wdPageBreak);
//add some more text
doc.Content.Text += "This line should be on the next page.";
//clean up
Marshal.FinalReleaseComObject(wordApp);
Marshal.FinalReleaseComObject(doc);
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();

Solution 2

If the location you would like to insert the page break is selected (by Word.Selection) :

The easiest way is to insert there the following code:

selection.TypeText("\f");
Share:
25,904
john
Author by

john

Updated on July 21, 2022

Comments

  • john
    john almost 2 years

    I trying to create a Word document via C#. I want to be able to insert a page break at a certain point in my code, however I am not sure on how to do this. I am mostly using StringBuilder to create the html. This is being done in Visual studios 2010 with c#. I've looked at some guides but most of them use code like "Word variable". So I'm not sure if "Word" comes from an extra downloaded library or what not.

    • Sorceri
      Sorceri over 11 years
      most likely the Word variable is because the added a reference to the Microsoft Word Library then used using Word = Microsoft.Office.interop.Word;
  • john
    john over 11 years
    I am creating all the content and appending it to a StringBuilder. Then I write the StringBuilder to a StreamWriter. When the While loop finishes it's first iteration of the data, I want to insert a page break. So that all the content of each iteration ison it's own page.
  • Mike M
    Mike M over 6 years
    indeed works great when I'm focused on outputting text line-by-line