Guides
Fill Form Fields
ComPDFKit
supports programmatically filling form fields in a PDF document.
The steps to fill in form fields using code are as follows:
Get the page object of the form to be filled in from CPDFDocument.
Retrieve all forms from the page object.
Traverse all forms to find the one to be filled in.
Modify the form field contents as needed.
This example shows how to fill in form fields:
tsx
const pageIndex = 0;
// Retrieve the page object of the first page
const cpdfPage: CPDFPage = pdfReaderRef?.current?._pdfDocument.pageAtIndex(pageIndex);
// Retrieve all form widgets on the current page
const widgets = await page?.getWidgets();
// Fill in the text field content
// Assume that there is a text field form on the current page and retrieve the CPDFTextWidget object
const textWidget = widgets[0] as CPDFTextWidget;
// Set the text field content to "Hello World"
await textWidget.setText('Hello World');
// Refresh the appearance of the form to apply changes, this step is necessary
await textWidget.updateAp();
// Modify the radio button's checked state
const radioButtonWidget = widgets[0] as CPDFRadiobuttonWidget;
// Set the radio button to checked
await radioButtonWidget.setChecked(true);
// Refresh the appearance of the radio button
await radioButtonWidget.updateAp();
// Modify the checkbox's checked state
const checkboxWidget = widgets[0] as CPDFCheckboxWidget;
// Set the checkbox to checked
await checkboxWidget.setChecked(true);
// Refresh the appearance of the checkbox
await checkboxWidget.updateAp();
// Add an electronic signature to the signature form
const signatureWidget = widgets[0] as CPDFSignatureWidget;
// Android-supported URI format:
await signatureWidget.addImageSignature('content://media/external/images/media/123');
// Or file path:
await signatureWidget.addImageSignature('/path/to/image');
// Refresh the appearance of the signature form
await signatureWidget.updateAp();