Aspose.Word page number in right margin

915 views Asked by At

i build document with Aspose.Word. I try add page number in right margin. Image better explain it:

My result pdf preview

How to do it?

My current code:

var document = new Document();
        _builder = new DocumentBuilder(document)
        {
            PageSetup =
            {
                Orientation = Orientation.Portrait,
                PaperSize = PaperSize.A4,
                RightMargin = ConvertUtil.MillimeterToPoint(20),
                BottomMargin = ConvertUtil.MillimeterToPoint(35),
                LeftMargin = ConvertUtil.MillimeterToPoint(35),
                TopMargin = ConvertUtil.MillimeterToPoint(35)
            }
        };

        _builder.StartTable();
        _builder.InsertCell();
        _builder.Write("Test test test");
        _builder.EndTable();

        _builder.MoveToHeaderFooter(HeaderFooterType.FooterPrimary);
        _builder.Write("Pages: ");
        _builder.InsertField("PAGE", "");
        _builder.Write("/");
        _builder.InsertField("NUMPAGES");
        document.Save(stream, SaveFormat.Pdf);
1

There are 1 answers

0
Tahir Manzoor On BEST ANSWER

In your case, you need to add text box in the footer of document, insert page number field in it, and set its position. Please use following modified code example to get the desired output.

var document = new Document();
DocumentBuilder _builder = new DocumentBuilder(document)
{
    PageSetup =
    {
        Orientation = Orientation.Portrait,
        PaperSize = Aspose.Words.PaperSize.A4,
        RightMargin = ConvertUtil.MillimeterToPoint(20),
        BottomMargin = ConvertUtil.MillimeterToPoint(35),
        LeftMargin = ConvertUtil.MillimeterToPoint(35),
        TopMargin = ConvertUtil.MillimeterToPoint(35)
    }
        };

_builder.StartTable();
_builder.InsertCell();
_builder.Write("Test test test");
_builder.EndTable();

_builder.MoveToHeaderFooter(HeaderFooterType.FooterPrimary);

Shape shape = new Shape(document, ShapeType.TextBox);
shape.Stroked = false;
shape.Width = _builder.CurrentSection.PageSetup.PageWidth;
shape.Height = 50;
shape.Left = 0;
shape.Left = - _builder.CurrentSection.PageSetup.LeftMargin; 
shape.Top = 0;

Paragraph paragraph = new Paragraph(document);
shape.AppendChild(paragraph);

_builder.InsertNode(shape);
_builder.MoveTo(paragraph);
_builder.ParagraphFormat.Alignment = ParagraphAlignment.Right;
_builder.Write("Pages: ");
_builder.InsertField("PAGE", "");
_builder.Write("/");
_builder.InsertField("NUMPAGES");
document.Save(MyDir + "output.pdf", SaveFormat.Pdf);

I work with Aspose as Developer evangelist.