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.
Put your cursor where you want one page to end and the next to begin. Go to Insert > 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.
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.
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();
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With