News Category

Insert page break at a specified location

2014-09-02 09:06:59 Written by  support iceblue
Rate this item
(0 votes)

Spire.Doc supports to insert page breaks in C# and VB.NET. We have already had a tutorial article of how to insert a page break after a paragraph. This article we will demonstrate how to add a page break at a specified location by searching a single word.

First, download Spire.Doc and install on your system. The Spire.Doc installation is clean, professional and wrapped up in a MSI installer. Then adds Spire.Doc.dll as reference in the downloaded Bin folder though the below path: "..\Spire.Doc\Bin\NET4.0\ Spire.Doc.dll".

Here comes to the steps of how to insert a page break at a specified location.

Step 1: Create a new word document and load the document from the file.

Document doc = new Document();
doc.LoadFromFile("Test.docx");

Step 2: Find the specified word "experience" where we want to insert the page break.

TextSelection[] selections = doc.FindAllString("experience", true, true);

Step 3: Traverse each word "experience".

foreach (TextSelection ts in selections)
   {
     TextRange range = ts.GetAsOneRange();
     Paragraph paragraph = range.OwnerParagraph;
     int index = paragraph.ChildObjects.IndexOf(range);
     Break pageBreak = new Break(doc, BreakType.PageBreak);
   }

Step 4: Create a new instance of page break and insert a page break after the word "experience".

Break pageBreak = new Break(doc, BreakType.PageBreak);
paragraph.ChildObjects.Insert(index + 1, pageBreak);

Step 5: Save the word document to file and process it.

doc.SaveToFile("Break.docx", FileFormat.Docx);
System.Diagnostics.Process.Start("Break.docx");

Effective screenshot of the inserted page break after the word "experience":

Insert page break at a specified location

Full codes:

using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
namespace InsertPageBreak
{
    class Program
    {
        static void Main(string[] args)
        {
            Document doc = new Document();
            doc.LoadFromFile("Test.docx");
            TextSelection[] selections = doc.FindAllString("experience", true, true);
            foreach (TextSelection ts in selections)
            {
                TextRange range = ts.GetAsOneRange();
                Paragraph paragraph = range.OwnerParagraph;
                int index = paragraph.ChildObjects.IndexOf(range);
                Break pageBreak = new Break(doc, BreakType.PageBreak);
                paragraph.ChildObjects.Insert(index + 1, pageBreak);
            }
            doc.SaveToFile("Break.docx", FileFormat.Docx);
            System.Diagnostics.Process.Start("Break.docx");
        }
    }
}

Additional Info

  • tutorial_title:
Last modified on Friday, 03 September 2021 03:36