Hi,
I want the code to add page numbers to a pdf file using c#. Can anyone help me out for the code .
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Marvin ReidPosted Nov 14, 2023, 2:15 PM
You can use the DocumentPage PageNumber property to first get the page number you are on, and then populate an AnnTextObject text annotation with that value. You can add this annotation onto each page of your PDF file.
Here is some code that demonstrates this:
Once that annotations are added, you can embed the text into your final output PDF file using a similar approach:
https://www.leadtools.com/help/sdk/dh/ac/anntextobject.html
https://www.leadtools.com/help/sdk/tutorials/dotnet-console-burn-annotations-to-a-leaddocument.html
Yashwanth MuthineniPosted Aug 1, 2015, 8:05 AM
Yashwanth MuthineniPosted Aug 1, 2015, 8:05 AM
Rajeesh MenothPosted Aug 1, 2015, 7:33 AM
Yashwanth MuthineniPosted Aug 1, 2015, 6:07 AM
Uehara AyakaPosted Jul 31, 2015, 2:39 AM
using Spire.Pdf;
using Spire.Pdf.Widget;
using Spire.Pdf.Graphics;
using System.Drawing;
namespace AddPageNumber2Pdf
{
class Program
{
static void Main(string[] args)
{
PdfDocument doc = new PdfDocument();
doc.LoadFromFile("Test.pdf");
//set the margin
PdfUnitConvertor unitCvtr = new PdfUnitConvertor();
PdfMargins margin = new PdfMargins();
margin.Top = unitCvtr.ConvertUnits(2.54f, PdfGraphicsUnit.Centimeter, PdfGraphicsUnit.Point);
margin.Bottom = margin.Top;
margin.Left = unitCvtr.ConvertUnits(3.17f, PdfGraphicsUnit.Centimeter, PdfGraphicsUnit.Point);
margin.Right = margin.Left;
//draw page number
DrawPageNumber(doc.Pages, margin, 1, doc.Pages.Count);
//save the file
doc.SaveToFile("AddNumber.pdf",FileFormat.PDF);
System.Diagnostics.Process.Start("AddNumber.pdf");
}
private static void DrawPageNumber(PdfPageCollection section, PdfMargins margin, int startNumber, int pageCount)
{
foreach (PdfPageBase page in section)
{
page.Canvas.SetTransparency(0.5f);
PdfBrush brush = PdfBrushes.Black;
PdfPen pen = new PdfPen(brush, 0.75f);
PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Arial", 10f, FontStyle.Bold), true);
PdfStringFormat format = new PdfStringFormat(PdfTextAlignment.Right);
format.MeasureTrailingSpaces = true;
float space = font.Height * 0.75f;
float x = margin.Left;
float width = page.Canvas.ClientSize.Width - margin.Left - margin.Right;
float y = page.Canvas.ClientSize.Height - margin.Bottom + space;
y = y + 1;
String numberLabel = String.Format("{0} of {1}", startNumber++, pageCount);
page.Canvas.DrawString(numberLabel, font, brush, x + width, y, format);
page.Canvas.SetTransparency(1);
}
}
}
}
Yashwanth MuthineniPosted Jul 21, 2015, 3:19 AM
Govinda Rajulu YemineniPosted Jul 21, 2015, 2:52 AM