Legacy notice!

iText 5 is the previous major version of iText's leading PDF SDK. iText 5 has been EOL, and is no longer developed. Switch your project to iText 7, integrating the latest developments.
Check related iText 7 content!

I am currently trying to fill out a predefined Form with itextsharp while adding an image. How can I do this?

All works well except adding an image. I was able to do this using a different library by changing the icon of a button in a predefined form. That scaled the image correctly. Unfortunatly I couldn't find any method to do this with iTextSharp.

This is what I've tried so far. It adds the image at an absolute position:

PdfContentByte pdfContentByte = pdfStamper.GetOverContent(1);
iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(picfile);
iTextSharp.text.Rectangle imageRect = new iTextSharp.text.Rectangle(338f, 65f, 250f, 200f, 270);
img.ScaleToFit(imageRect.Width, imageRect.Height);
img.SetAbsolutePosition(65, 250);

Unfortunately, the image isn't sized correctly. I think there must be a better way to do this.5

Posted on StackOverflow on Oct 23, 2012 by xXx

Your code sample simply adds an image to the content of a page. As you indicate, that's not what you want. You want to replace the icon in a button field. This can be done using this code snippet:

AcroFields form = stamper.AcroFields;
PushbuttonField ad = form.GetNewPushbuttonFromField(buttonFieldName);
ad.Layout = PushbuttonField.LAYOUT_ICON_ONLY;
ad.ProportionalIcon = true;
ad.Image = Image.GetInstance(pathToNewImage);
form.ReplacePushbuttonField("advertisement", ad.Field);

For examples, take a look at the ReplaceIcon example, the MovieAds example, and the ChangeButton example.