Friday, June 11, 2010

Add an image at a given position without fail on any page of a pdf file.

Looking for a way to add an image at a given position on a pdf ( Provided you use iTextSharp for .Net library). Here is the way to go.


Following code is an extract from here.


string pdfTemplate = @"c:\Temp\PDF\fw4.pdf";
string newFile = @"c:\Temp\PDF\completed_fw4.pdf";


PdfReader pdfReader = new PdfReader(pdfTemplate);
PdfStamper pdfStamper = new PdfStamper(pdfReader, new FileStream(
newFile, FileMode.Create));
AcroFields pdfFormFields = pdfStamper.AcroFields;
string chartLoc = string.Empty;
chartLoc = @"C:\Temp\PDF\IMG_3746.jpg";//pplLogoSmall.jpg";


iTextSharp.text.Image chartImg = iTextSharp.text.Image.GetInstance(chartLoc);
iTextSharp.text.pdf.PdfContentByte overContent;


iTextSharp.text.Rectangle rect;
try
{
Single X, Y;int pageCount = 0;
rect = pdfReader.GetPageSizeWithRotation(1);
if (chartImg.Width > rect.Width || chartImg.Height > rect.Height)
{
chartImg.ScaleToFit(rect.Width, rect.Height);
X = (rect.Width - chartImg.ScaledWidth) / 2;
Y = (rect.Height - chartImg.ScaledHeight) / 2;
}
else
{
X = (rect.Width - chartImg.Width) / 2;
Y = (rect.Height - chartImg.Height) / 2;
}
chartImg.SetAbsolutePosition(X, Y);
pageCount = pdfReader.NumberOfPages;
for (int i = 1; i < pageCount; i++)
{
overContent = pdfStamper.GetOverContent(i);
overContent.AddImage(chartImg);
}
pdfStamper.Close();
pdfReader.Close();
}
catch (Exception ex)
{
throw ex;
}

Happy Coding!

No comments:

Post a Comment