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:

swift
var document = CPDFDocument(url: URL(string: "filePath"))
let page = document?.page(at: 0)

if let annotations = page?.annotations as? [CPDFAnnotation] {
    for annotation in annotations {
        if let widgetAnnotation = annotation as? CPDFWidgetAnnotation {
            if let textWidget = widgetAnnotation as? CPDFTextWidgetAnnotation {
                textWidget.stringValue = "text"
            } else if let buttonWidget = widgetAnnotation as? CPDFButtonWidgetAnnotation {
                switch buttonWidget.controlType() {
                case .radioButtonControl:
                   
                    break
                case .pushButtonControl:
                   
                    break
                case .checkBoxControl:
                   
                    break
                default:
                    break
                }
            } else if let choiceWidget = widgetAnnotation as? CPDFChoiceWidgetAnnotation {
                
            }
        }
    }
}
objective-c
CPDFDocument *document = [[CPDFDocument alloc] initWithURL:[NSURL fileURLWithPath:@"filePath"]];
CPDFPage *page = [document pageAtIndex:0];

NSArray *annotations = [page annotations];
for (CPDFAnnotation *annotationz in annotations) {
    if([annotationz isKindOfClass:[CPDFWidgetAnnotation class]]) {
        CPDFWidgetAnnotation * annotation = (CPDFWidgetAnnotation *)annotationz;

        ((CPDFTextWidgetAnnotation*)annotation).stringValue = "text"
      } else if ([annotation isKindOfClass:[CPDFButtonWidgetAnnotation class]]) {
          if (CPDFWidgetRadioButtonControl == [(CPDFButtonWidgetAnnotation *)annotation controlType]{

          } else if (CPDFWidgetPushButtonControl == [(CPDFButtonWidgetAnnotation *)annotation controlType]) {

              }
          } else if (CPDFWidgetCheckBoxControl == [(CPDFButtonWidgetAnnotation *)annotation controlType]{

          }
      } else if ([annotation isKindOfClass:[CPDFChoiceWidgetAnnotation class]]) {

      }

  }
}