Hi,
I likte to put the pagenumer on every page in the footer, but aligned to the page center.
RectangleF bounds = new(0, 0, document.Pages[0].GetClientSize().Width, 50);
PdfPageTemplateElement footer = new (bounds);
PdfPageNumberField pageNumber = new(PdfStyles.fontNormal);
PdfPageCountField count = new(PdfStyles.fontNormal);
PdfCompositeField compositeField = new(PdfStyles.fontNormal, "Page {0} of {1}", pageNumber, count)
{
Bounds = footer.Bounds
};
compositeField.Draw(footer.Graphics, new PointF(0, 0));
document.Template.Bottom = footer;
creates the text I want, but I do not know how to align the text in the footer.
I can shift the text, by changing the xPosition in .Draw, but this is not coorect, because the text length is not recognized.
I tried to use a grid with cell alignment but there I can not use the compositeField als Value of the cell.
So how can I pace the footer text with the correct alignment on every page?
Best regards
Alex
Hi Alexander Kuhlmann,
We don't have alignment support for the footer page number field. As a workaround we can measure the footer text and center it using the following code.
static void CreatePDF()
{
//Create a new PDF document
PdfDocument document = new PdfDocument();
//Add a page to the document
PdfPage page = document.Pages.Add();
//Create footer
PdfPageTemplateElement footer = CreateFooter(page.GetClientSize());
//Assign the footer to the document
document.Template.Bottom = footer;
//Add page to the document
page = document.Pages.Add();
//Save the document
MemoryStream stream = new MemoryStream();
document.Save(stream);
document.Close(true);
File.WriteAllBytes("Output.pdf", stream.ToArray());
}
static PdfPageTemplateElement CreateFooter(SizeF size)
{
//Create a Page template that can be used as footer.
PdfPageTemplateElement footer = new PdfPageTemplateElement(new RectangleF(0, 0, size.Width, 50));
//Create font
PdfFont font = new PdfStandardFont(PdfFontFamily.Helvetica, 12);
//Create brush
PdfBrush brush = new PdfSolidBrush(Color.Black);
//Create page number field.
PdfPageNumberField pageNumber = new PdfPageNumberField(font, brush);
//Create page count field.
PdfPageCountField count = new PdfPageCountField(font, brush);
//Add the fields in composite fields.
PdfCompositeField compositeField = new PdfCompositeField(font, brush, "Page {0} of {1}", pageNumber, count);
compositeField.Bounds = footer.Bounds;
//Assume that the PDF document is going to generate up to 99 pages.
SizeF textSize = font.MeasureString("Page 99 of 99");
//Get the center x and y position.
float x = (footer.Width / 2) - (textSize.Width / 2);
float y = (footer.Height / 2) - (textSize.Height / 2);
//Draw the composite field in footer.
compositeField.Draw(footer.Graphics, new PointF(x, y));
//return the footer
return footer;
}
Regards,
Jeyalakshmi T