Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert Page break when creating MS Word document

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.

like image 472
john Avatar asked Nov 07 '12 19:11

john


People also ask

How do you insert a page break?

Put your cursor where you want one page to end and the next to begin. Go to Insert > Page Break.

Which option is used for inserting page break?

Insert Page Breaks Click to place your cursor where you want to start a new page. Click the Insert tab. If necessary, expand the Pages group by clicking it. Click the Page Break button.

Why won't Microsoft Word Let me insert a page break?

Scroll down until you see the Page Layout options (Compatibility Options in Word 2019 and Word in Office 365). It is at the very bottom of the dialog box; you may need to click the arrow at the left side of the options to see them all. Make sure the Split Apart Page Break and Paragraph Mark check box is selected.


2 Answers

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();
like image 163
Sorceri Avatar answered Sep 30 '22 18:09

Sorceri


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");
like image 22
user3165438 Avatar answered Sep 30 '22 17:09

user3165438