Friday, 15 December 2017

add page number to pdf footer using itextsharp

Namespaces
You will need to import the following namespaces.
C#
using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;
 
VB.Net
Imports System.IO
Imports iTextSharp.text
Imports iTextSharp.text.pdf
 
 
Adding Page numbers to existing PDF
The PDF file to which the page numbers needs to be added is read into a Byte array from the disk. Then the byte array is read into a PdfReader object and a loop is executed over the pages of the PDF and the page number is added to each page using the PdfStamper class.
Finally the MemoryStream is saved to disk as PDF file.
C#
protected void AddPageNumber(object sender, EventArgs e)
{
    byte[] bytes = File.ReadAllBytes(@"D:\PDFs\Test.pdf");
    Font blackFont = FontFactory.GetFont("Arial", 12, Font.NORMAL, BaseColor.BLACK);
    using (MemoryStream stream = new MemoryStream())
    {
        PdfReader reader = new PdfReader(bytes);
        using (PdfStamper stamper = new PdfStamper(reader, stream))
        {
            int pages = reader.NumberOfPages;
            for (int i = 1; i <= pages; i++)
            {
                ColumnText.ShowTextAligned(stamper.GetUnderContent(i), Element.ALIGN_RIGHT, new Phrase(i.ToString(), blackFont), 568f, 15f, 0);
            }
        }
        bytes = stream.ToArray();
    }
    File.WriteAllBytes(@"D:\PDFs\Test_1.pdf", bytes);
}
 
VB.Net
Protected Sub AddPageNumber(sender As Object, e As EventArgs)
    Dim bytes As Byte() = File.ReadAllBytes("D:\PDFs\Test.pdf")
    Dim blackFont As Font = FontFactory.GetFont("Arial", 12, Font.NORMAL, BaseColor.BLACK)
    Using stream As New MemoryStream()
        Dim reader As New PdfReader(bytes)
        Using stamper As New PdfStamper(reader, stream)
            Dim pages As Integer = reader.NumberOfPages
            For i As Integer = 1 To pages
                ColumnText.ShowTextAligned(stamper.GetUnderContent(i), Element.ALIGN_RIGHT, New Phrase(i.ToString(), blackFont), 568.0F, 15.0F, 0)
            Next
        End Using
        bytes = stream.ToArray()
    End Using
    File.WriteAllBytes("D:\PDFs\Test_1.pdf", bytes)
End Sub

No comments:

Post a Comment

How to get the value from web.config(if any value assign as static Key)

Web.Config File:   <appSettings>     <add key="DomainName" value="PW" />     </appSettings> Cl...