Make a Word document with multiple pages in C#

[Word document]

The example Create a Word document in C# shows how to create a Word document and save it into a file. See that example for the basics including how to create the document, add paragraphs to it, and save it into a file.

This example shows how to make a multi-page Word document. The following snippet shows the key pieces of code.

// Page 1.
// Create a header paragraph.
Word.Paragraph para = word_doc.Paragraphs.Add(ref missing);
para.Range.Text = "First Page";
object heading1_name = "Heading 1";
para.Range.set_Style(ref heading1_name);
para.Range.InsertParagraphAfter();

// Add more text.
para.Range.Text = "Here is some text for the first page.";
para.Range.InsertParagraphAfter();

// Add a page break.
object break_type = Word.WdBreakType.wdPageBreak;
para.Range.InsertBreak(ref break_type);

// Page 2.
// Create a header paragraph.
para = word_doc.Paragraphs.Add(ref missing);
para.Range.Text = "Second Page";
para.Range.set_Style(ref heading1_name);
para.Range.InsertParagraphAfter();

// Add more text.
para.Range.Text = "Here is some text for the second page.";
para.Range.InsertParagraphAfter();

After creating the Word document (not shown), the program creates a Paragraph object. It sets the paragraph’s text to “First Page” and sets its style to “Heading 1.” It then calls the InsertParagraphAfter method to insert a paragraph break after the text. That advances the Paragraph object so it points to the spot after its initial position. In other words, it moves the paragraph after the first line of text and the paragraph break.

Next the code sets the object’s text to some more text.

If you wanted to add more text to the first page, you would repeat these steps:

  • Set the Paragraph object’s text.
  • Optionally set the paragraph’s style.
  • Call InsertParagraphAfter to add a paragraph break.

After finishing the first page, the code calls the InsertBreak method to add a page break. It then repeats the earlier steps to create a second page.

See the earlier example and download this example to see additional details about how to create and save the Word document.


Download Example   Follow me on Twitter   RSS feed   Donate




About RodStephens

Rod Stephens is a software consultant and author who has written more than 30 books and 250 magazine articles covering C#, Visual Basic, Visual Basic for Applications, Delphi, and Java.
This entry was posted in interoperability, Office, Word and tagged , , , , , , , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.