Skip to content
Guides

Fill Form Fields

ComPDFKit supports programmatically filling form fields in a PDF document.

Since form fields are a special type of annotation, inheriting from the annotation class, the interface for annotations applies to form fields.

The steps to fill form fields using code are as follows:

  1. Obtain the page object from CPDFDocument where you want to fill in the form.

  2. Retrieve all annotations from the page object.

  3. Iterate through all annotations to find the form to be filled.

  4. Modify the form field content as needed.

This example shows how to fill form fields:

java
CPDFDocument document = new CPDFDocument(context);
document.open(pdfPath);

for (int i = 0; i < document.getPageCount(); i++) {
  CPDFPage page = document.pageAtIndex(i);
  for (CPDFAnnotation annotation : page.getAnnotations()) {
    switch (annotation.getType()) {
      case WIDGET:
        CPDFWidget cpdfWidget = (CPDFWidget) annotation;
        switch (cpdfWidget.getWidgetType()) {
          case Widget_TextField:
            CPDFTextWidget textWidget = (CPDFTextWidget) cpdfWidget;
            textWidget.setText("test");
            textWidget.updateAp();
            break;
          case Widget_RadioButton:
            CPDFRadiobuttonWidget radiobuttonWidget = (CPDFRadiobuttonWidget) cpdfWidget;
            radiobuttonWidget.setChecked(true);
            radiobuttonWidget.updateAp();
            break;
          case Widget_ListBox:
            CPDFListboxWidget listBoxWidget = (CPDFListboxWidget) cpdfWidget;
            listBoxWidget.setSelectedIndexes(new int[]{0});
            listBoxWidget.updateAp();
            break;
          default:
            break;
        }
        break;
      default:
        break;
    }
  }
}
kotlin
val document = new CPDFDocument(context)
document.open(pdfPath)

for (i in 0 until document.pageCount) {
  val page = document.pageAtIndex(i)
  for (annotation in page.annotations) {
    when (annotation.type) {
      CPDFAnnotation.Type.WIDGET -> {
        val cpdfWidget = annotation as CPDFWidget
        when (cpdfWidget.widgetType) {
          WidgetType.Widget_TextField -> {
            val textWidget = cpdfWidget as CPDFTextWidget
            textWidget.text = "test"
            textWidget.updateAp()
          }
          WidgetType.Widget_RadioButton -> {
            val radioButtonWidth = cpdfWidget as CPDFRadiobuttonWidget
            radioButtonWidth.isChecked = true
            radioButtonWidth.updateAp()
          }
          WidgetType.Widget_ListBox -> {
            val listBoxWidget = cpdfWidget as CPDFListboxWidget
            listBoxWidget.selectedIndexes = intArrayOf(0)
            listBoxWidget.updateAp()
          }
          else -> {}
        }
      }
      else -> {}
    }
  }
}