How to add page Number. in Aspose.Word

Hi

I am Exporting MSWORD from HTML Stream using Aspose.Word .

I use builder.InsertHTML() to which I pass HTML stream . To add page break I use this

<p style='ms-special-character:line-break;page-break-before:always'>&nbsp;</p>

which works fine it adds page break and all that …

Now I wan to add Header and Footer and in Footer I want to show page number.

at some point I want to reset page no. to 1 again

How to achieve this ?

Regards ,
Jeevan Joshi.

Hi Jeevan,

Thanks for your inquiry. Please note that you can not insert header/footer by using DocumentBuilder.InsertHtml method.

The HeaderFooter class represents a container for the header or footer text of a section. HeaderFooter is a section-level node and can only be a child of Section. So, header and footer repeat on each page of a section. There can only be one HeaderFooter or each HeaderFooterType in a Section.

You can insert header/footer after calling DocumentBuilder.InsertHtml method and insert page number field in footer of a section as shown in following code snippet.

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

builder.InsertHtml("<P align='right'>Paragraph right</P>" +
    "<b>Implicit paragraph left</b>" +
    "<div align='center'>Div center</div>" +
    "<h1 align='left'>Heading 1 left.</h1>");

InsertHeaderFooter(builder.CurrentSection, HeaderFooterType.FooterPrimary);
InsertHeaderFooter(builder.CurrentSection, HeaderFooterType.HeaderFirst);

builder.MoveToHeaderFooter(HeaderFooterType.FooterPrimary);
//Set start number
builder.PageSetup.PageStartingNumber = 1;
//Page numbers will be restarted for each section
builder.PageSetup.RestartPageNumbering = true;
//Insert PAGE field into the header
builder.MoveToHeaderFooter(HeaderFooterType.FooterPrimary);
builder.Write("Page");
builder.InsertField("PAGE", string.Empty);
builder.MoveToDocumentEnd();
//Insert page break
builder.InsertBreak(BreakType.PageBreak);
//Insert section break
builder.InsertBreak(BreakType.SectionBreakNewPage);

doc.Save(MyDir + "Out.docx");
private static void InsertHeaderFooter(Section sect, HeaderFooterType headerType)
{
    HeaderFooter header = sect.HeadersFooters[headerType];

    if (header == null)
    {
        // There is no header of the specified type in the current section, create it.
        header = new HeaderFooter(sect.Document, headerType);
        sect.HeadersFooters.Add(header);
    }
}

Section can have one Body and maximum one HeaderFooter of each HeaderFooterType. Body and HeaderFooter nodes can be in any order inside Section.
Please read following documentation link for your kind reference.
https://docs.aspose.com/words/net/working-with-sections/
https://docs.aspose.com/words/net/working-with-headers-and-footers/

Hope this helps you. Please let us know if you have any more queries.