Replace field with image

This code sample opens a PDF with a textfield and replaces this textfield with an image. The image has the same width and its aspect ratio is preserved. The top-left corner of the image is placed at the top-left corner of the field.

Replace Field

// open textField.pdf
using (FileStream fileIn = new FileStream("textfield.pdf", FileMode.Open))
{
  Document pdf = new Document(fileIn);

  // get the widget of field 'textField'
  TextField field = pdf.Fields["textField"] as TextField;
  Widget widget = field.Widgets[0];

  // create a new image an place it over the widget
  ImageShape image = new ImageShape("pyramid.png");
  image.Width = widget.Width;
  image.KeepAspectRatio = true;
  image.Transform = new TranslateTransform(widget.Left, widget.Top - image.Height);
  pdf.Pages[0].Overlay.Add(image);

  // remove the widget when saving
  widget.Persistency = WidgetPersistency.Remove;
                
  // save as image.pdf
  using (FileStream fileOut = new FileStream("image.pdf", FileMode.Create))
  {
    pdf.Write(fileOut);
  }
}