How to: Replace a Form Field with an Image

  • 4 minutes to read

This topic describes how to substitute an interactive form field in a PDF document with an image. To perform this task, remove the required form field from the document and display an image instead of the deleted field. Form field removal is necessary, because widget annotation is drawn over the page content and can overlap an image added at the form field’s position.

Follow the steps below to replace a form field with an image that maintains the same size and position.

using System.Drawing;
using DevExpress.Pdf;

static void Main(string[] args)
{
    const float dpix = 72f;
    const float dpiY = 72f;
  using (PdfDocumentProcessor processor = new PdfDocumentProcessor())
  {

    // Load a PDF document with AcroForm data. 
    processor.LoadDocument("..\\..\\InteractiveForm.pdf");
    PdfDocumentFacade documentFacade = processor.DocumentFacade;
    PdfAcroFormFacade acroForm = documentFacade.AcroForm;
    string fieldName = "Address";
    PdfTextFormFieldFacade formField = acroForm.GetFormField(fieldName) as PdfTextFormFieldFacade;
    if (formField == null) return;

    foreach (PdfWidgetFacade widget in formField)
    {
        PdfRectangle rect = widget.Rectangle;
        PdfPage page = processor.Document.Pages[widget.PageNumber - 1];
        double x = rect.Left - page.CropBox.Left;
        double y = page.CropBox.Top - rect.Bottom;

        // Create graphics and draw an image.
        using (PdfGraphics graphics = processor.CreateGraphics())
        {
            DrawImage(graphics, rect, x, y);

            graphics.AddToPageForeground(page, dpix, dpiY);
        }


    }
    processor.RemoveFormField(fieldName);
    processor.SaveDocument("..\\..\\Result.pdf");
  }
}

static void DrawImage(PdfGraphics graphics, PdfRectangle rect, double x, double y)
{

    Bitmap image = new Bitmap("..\\..\\AddressFormField.png");

    double aspectRatio = image.Width / image.Height;

    double scaleX = image.Width / rect.Width;
    double scaleY = image.Height / rect.Height;

    double width;
    double height;

    if (scaleX < scaleY) {

        width = rect.Width;
        height = width / aspectRatio;
    }

    else {
        height = rect.Height;
        width = height * aspectRatio;
    }

    RectangleF imageRect = new RectangleF((float)x, (float)(y - height), (float)width, (float)height);
    graphics.DrawImage(image, imageRect);
}
See Also