Sandip Gend Sandip Gend - 14 days ago 5
C# Question

Add image with text in header of every page in pdf file using itextsharp

When we use below code it add only one image. Is any other option to add image & text on every page?

private void AddHeader(string filephysicalpath, string nfile)
{
byte[] bytes = System.IO.File.ReadAllBytes(filephysicalpath);
String path = ConfigurationManager.AppSettings["Documentheader"].ToString() + Session["headerImg"];
Stream inputImageStream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read);

Font blackFont = FontFactory.GetFont("Arial", 12, Font.BOLD, 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++)
{
string footer = Convert.ToString(Session["Footer"]);
if (Session["Footer"] != null)
{
// Phrase ft = new Phrase(footer, blackFont);
float marginLR = 36;
float marginB = 2;
float footerHeight = 10;
Rectangle pagesize = reader.GetCropBox(i);
if (pagesize == null)
{
pagesize = reader.GetPageSize(i);
}
Rectangle rect = new Rectangle(
pagesize.Left + marginLR, pagesize.Top + marginB,
pagesize.Right - marginLR, pagesize.Top + marginB + footerHeight
);



iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(inputImageStream);
image.SetAbsolutePosition(rect.Left, rect.Top - image.ScaledHeight);
var pdfContentByte = stamper.GetOverContent(1);
pdfContentByte.AddImage(image);
inputImageStream.Seek(0L, SeekOrigin.Begin);
// ct.AddElement(new PdfPTableHeader (image));

}
}
}
reader.Close();
bytes = stream.ToArray();
}
System.IO.File.WriteAllBytes(filephysicalpath, bytes);
}

mkl mkl
Answer

In your loop you do

       var pdfContentByte = stamper.GetOverContent(1);
       pdfContentByte.AddImage(image);

I.e. you always use the OverContent of page 1 and add the image to it. Instead you should use the OverContent of page i:

       var pdfContentByte = stamper.GetOverContent(i);
       pdfContentByte.AddImage(image);

Furthermore, you should import the image only once, i.e. move the line

     iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(inputImageStream);

above the loop.