Add footer only on last page of RTF file from html template

Hi,

I want to insert footer only on last page of the .rtf file from an HTML template. Is there any way to do that? Currently it adds the footer to all pages.
Following is my code:

var htmlStr = GetHtml(templateModel.BodyTemplate, handlebarModel);
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

builder.InsertHtml(htmlStr);
builder.PageSetup.BottomMargin = ConvertUtil.InchToPoint(Margin);
builder.PageSetup.TopMargin = ConvertUtil.InchToPoint(Margin);
builder.PageSetup.LeftMargin = ConvertUtil.InchToPoint(Margin);
builder.PageSetup.RightMargin = ConvertUtil.InchToPoint(Margin);
builder.PageSetup.FooterDistance = ConvertUtil.InchToPoint(FooterDistance);

var htmlTemplateFooter = GetHtml(templateModel.FooterTemplate, handlebarModel);
builder.MoveToHeaderFooter(HeaderFooterType.FooterPrimary);
builder.InsertHtml(htmlTemplateFooter);

doc.Save($"{@"C:\Documents\New folder\AsposeRTF" + DateTime.Now.ToString("MMddyyyyhmmttfff")}.rtf", SaveFormat.Rtf);

@sophiakhan,

You can make use of IF, PAGE and NUMPAGES fields to show content only inside the footer of last Page of Word RTF document. Please check the following C# code of Aspose.Words for .NET API:

var htmlTemplateFooter = "<b>Bold Text</b>";

Document doc = new Document("C:\\Temp\\input.docx");
DocumentBuilder builder = new DocumentBuilder(doc);

builder.MoveToHeaderFooter(HeaderFooterType.FooterPrimary);

FieldIf fieldIf = (FieldIf)builder.InsertField(FieldType.FieldIf, false);
builder.MoveTo(fieldIf.Separator);

builder.InsertField(FieldType.FieldPage, true);
builder.Write(" = ");
builder.InsertField(FieldType.FieldNumPages, true);
builder.Write(" \"");
builder.InsertHtml(htmlTemplateFooter, true);
builder.Write("\"");

doc.UpdateFields();

doc.Save(@"C:\Temp\21.1.rtf");
1 Like

Thanks this worked, I did need to remove line doc.UpdateFields(); for it to work though.

@sophiakhan,

It is great that you were able to find what you were looking for. Please let us know any time you may have any further queries in future.

@awais.hafeez So this works except for if the document is only one page. My expectation would be that the footer appears on the first page if there is only one page in the document. Can you help with that?

@sophiakhan,

After an initial test with the licensed latest (21.1) version of Aspose.Words for .NET, we were unable to reproduce this issue on our end. Please ZIP and upload your one-page input Word document and Aspose.Words generated output DOCX file showing the undesired behavior here for testing. We will then investigate the issue on our end and provide you more information.