From 752f229b6d97f4c4712f6b4e01b17200688e2d90 Mon Sep 17 00:00:00 2001 From: Balaji Loganathan Date: Tue, 10 Mar 2026 17:35:36 +0530 Subject: [PATCH] 1013392: Moved forms module changes to hotfix --- Document-Processing-toc.html | 3 + .../react/forms/flatten-form-fields.md | 121 +++++ .../PDF-Viewer/react/forms/form-designer.md | 251 ++-------- .../react/forms/form-field-events.md | 48 +- .../PDF-Viewer/react/forms/form-filling.md | 473 +++++++----------- .../export-form-fields.md | 260 ++++------ .../import-form-fields.md | 225 +++------ .../manage-form-fields/create-form-fields.md | 101 ++-- .../react/forms/read-form-field-values.md | 106 ++++ .../react/forms/submit-form-data.md | 121 +++++ .../how-to/add-annotation-in-text-search.md | 255 ++++++---- 11 files changed, 983 insertions(+), 981 deletions(-) create mode 100644 Document-Processing/PDF/PDF-Viewer/react/forms/flatten-form-fields.md create mode 100644 Document-Processing/PDF/PDF-Viewer/react/forms/read-form-field-values.md create mode 100644 Document-Processing/PDF/PDF-Viewer/react/forms/submit-form-data.md diff --git a/Document-Processing-toc.html b/Document-Processing-toc.html index 5c7f2a69c4..87b5f74d63 100644 --- a/Document-Processing-toc.html +++ b/Document-Processing-toc.html @@ -1058,6 +1058,9 @@
  • Custom fonts
  • Form Field events
  • APIs
  • +
  • Flatten form fields
  • +
  • Read form fields
  • +
  • Submit form data
  • Organize Pages diff --git a/Document-Processing/PDF/PDF-Viewer/react/forms/flatten-form-fields.md b/Document-Processing/PDF/PDF-Viewer/react/forms/flatten-form-fields.md new file mode 100644 index 0000000000..5dd2386e28 --- /dev/null +++ b/Document-Processing/PDF/PDF-Viewer/react/forms/flatten-form-fields.md @@ -0,0 +1,121 @@ +--- +layout: post +title: Flatten PDF form fields in React PDF Viewer | Syncfusion +description: Learn hoow to flatten interactive PDF form fields before download or save-as in EJ2 React PDF Viewer. +platform: document-processing +control: PDF Viewer +documentation: ug +domainurl: ##DomainURL## +--- + +# Flatten PDF form fields in React + +## Overview + +Flattening PDF forms converts interactive fields such as textboxes, dropdowns, checkboxes, signatures, etc., into non‑editable page content. Use this when you want to protect filled data, finalize a document, or prepare it for secure sharing. + +## Prerequisites + +- EJ2 React PDF Viewer installed and configured +- Basic viewer setup completed with toolbar and page organizer services injected. For more information, see [getting started guide](../getting-started) + +## Flatten forms before downloading PDF + +1. Add a ref to the `PdfViewerComponent` so you can access viewer APIs from event handlers. +2. Intercept the download flow using `downloadStart` and cancel the default flow. +3. Retrieve the viewer's blob via `saveAsBlob()` and convert the blob to base64. +4. Use `PdfDocument` from Syncfusion PDF Library to open the document, set `field.flatten = true` for each form field, then save. +5. For the flattening the form fields when downloading through *Save As* option in Page Organizer, repeat steps 2–4 by using `pageOrganizerSaveAs` event. + +## Complete example + +{% tabs %} +{% highlight ts tabtitle="App.tsx" %} +{% raw %} +import { + PdfViewerComponent, Toolbar, Magnification, Navigation, Annotation, LinkAnnotation, + ThumbnailView, BookmarkView, TextSelection, TextSearch, FormFields, FormDesigner, + PageOrganizer, Inject, Print, PageOrganizerSaveAsEventArgs, DownloadStartEventArgs +} from '@syncfusion/ej2-react-pdfviewer'; +import { PdfDocument, PdfField } from '@syncfusion/ej2-pdf'; +import { RefObject, useRef } from 'react'; + +export default function App() { + const viewerRef: RefObject = useRef(null); + + const blobToBase64 = async (blob: Blob): Promise => { + return new Promise((resolve, reject) => { + const reader = new FileReader(); + reader.onerror = () => reject(reader.error); + reader.onload = () => { + const dataUrl: string = reader.result as string; + const data: string = dataUrl.split(',')[1]; + resolve(data); + }; + reader.readAsDataURL(blob); + }); + } + + const flattenFormFields = (data: string) => { + let document: PdfDocument = new PdfDocument(data); + for (let index = 0; index < document.form.count; index++) { + let field: PdfField = document.form.fieldAt(index); + field.flatten = true; + } + // If both annotations and form fields needs to be flattened, use + // document.flatten = true + document.save(`${viewerRef.current.fileName}.pdf`); + document.destroy(); + } + + const handleFlattening = async () => { + const blob: Blob = await viewerRef.current.saveAsBlob(); + const data: string = await blobToBase64(blob); + flattenFormFields(data); + } + + const onDownloadStart = async (args: DownloadStartEventArgs) => { + args.cancel = true; + handleFlattening(); + }; + + const onPageOrganizerSaveAs = async (args: PageOrganizerSaveAsEventArgs) => { + args.cancel = true; + handleFlattening() + }; + + return ( +
    + + + +
    + ); +} +{% endraw %} +{% endhighlight %} +{% endtabs %} + +## Expected result + +- The downloaded or "Save As" PDF will contain the visible appearance of filled form fields as static, non-editable content. +- Form fields will no longer be interactive or editable in common PDF readers. + +## Troubleshooting + +- If viewerRef is null, ensure `ref={viewerRef}` is present and the component has mounted before invoking `saveAsBlob()`. +- Missing `resourceUrl`: If viewer resources are not reachable, set `resourceUrl` to the correct CDN or local path for the ej2-pdfviewer-lib. + +## Related topics + +- [`downloadStart` event reference](../events#downloadstart) +- [`pageOrganizerSaveAs` event reference](../events#pageorganizersaveas) +- [Form Designer in React PDF Viewer](./form-designer) \ No newline at end of file diff --git a/Document-Processing/PDF/PDF-Viewer/react/forms/form-designer.md b/Document-Processing/PDF/PDF-Viewer/react/forms/form-designer.md index e7e1264e39..72139f7f8c 100644 --- a/Document-Processing/PDF/PDF-Viewer/react/forms/form-designer.md +++ b/Document-Processing/PDF/PDF-Viewer/react/forms/form-designer.md @@ -16,8 +16,8 @@ Using the Form Designer UI, users can place form fields on the PDF, move and res ## Key Features -**Add Form Fields** -You can add the following form fields to the PDF: +**Add Form Fields:** +The following form fields can be added to the PDF: - [Text box](../forms/manage-form-fields/create-form-fields#add-textbox) - [Password Field](../forms/manage-form-fields/create-form-fields#add-password) @@ -28,24 +28,32 @@ You can add the following form fields to the PDF: - [Signature field](../forms/manage-form-fields/create-form-fields#add-signature-field) - [Initial field](../forms/manage-form-fields/create-form-fields#add-initial-field) -**Edit Form Fields** -You can move, resize, align, distribute, copy, paste, and undo or redo changes to form fields. +**Edit Form Fields:** +Form fields can be moved, resized, aligned, distributed, copied, pasted, and have changes undone or redone. -**Set Field Properties** -You can configure field properties such as name, value, font, color, border, alignment, visibility, tab order, and required or read only state. +**Set Field Properties:** +Field properties such as name, value, font, color, border, alignment, visibility, tab order, and required or read-only state can be configured. -**Control Field Behavior** -You can enable or disable read only mode, show or hide fields, and control whether fields appear when printing the document. +**Control Field Behavior:** +Field behavior can be controlled, including enabling or disabling read-only mode, showing or hiding fields, and determining whether fields appear when printing the document. -**Manage Form Fields** -You can select, group or ungroup, reorder, and delete form fields as needed. +**Manage Form Fields:** +Form fields can be selected, grouped or ungrouped, reordered, and deleted as needed. -**Save and Print Forms** +**Save and Print Forms:** Designed form fields can be saved into the PDF document and printed with their appearances. -## Enable Form Designer +## Design Forms with UI interaction -To enable form design features, inject the [FormDesigner](https://ej2.syncfusion.com/react/documentation/api/pdfviewer/formdesigner) module into the PDF Viewer. After injecting the module, use the [enableFormDesigner](https://ej2.syncfusion.com/react/documentation/api/pdfviewer/index-default#enableformdesigner) API to show or hide the Form Designer option in the main toolbar. +When [Form Designer mode](https://ej2.syncfusion.com/react/documentation/api/pdfviewer/formdesigner) is enabled in the Syncfusion [React PDF Viewer](https://help.syncfusion.com/document-processing/pdf/pdf-viewer/react/overview), a default [Form Designer user interface (UI)](https://document.syncfusion.com/demos/pdf-viewer/react/#/tailwind3/pdfviewer/form-designer) is displayed. This UI provides a built in toolbar for adding common form fields such as text boxes, check boxes, radio buttons, drop down lists, and signature fields. Users can place fields on the PDF, select them, resize or move them, and configure their properties using the available editing options, enabling interactive form creation directly within the viewer. + +![FormDesigner](../../javascript-es6/images/FormDesigner.gif) + +For more information about creating and editing form fields in the PDF Viewer, refer to the [Form Creation](./manage-form-fields/create-form-fields) in React PDF Viewer documentation. + +### Enable Form Designer + +Form design features are enabled by injecting the [FormDesigner](https://ej2.syncfusion.com/react/documentation/api/pdfviewer/formdesigner) module into the PDF Viewer. The [enableFormDesigner](https://ej2.syncfusion.com/react/documentation/api/pdfviewer/index-default#enableformdesigner) API controls whether the Form Designer option appears in the main toolbar. {% tabs %} {% highlight js tabtitle="index.js" %} @@ -64,7 +72,7 @@ export function App() { style={{ 'height': '680px' }} > + Print, TextSelection, TextSearch, FormFields, FormDesigner]} />
    ); @@ -74,17 +82,7 @@ root.render(); {% endhighlight %} {% endtabs %} -## Form Designer UI - -When [Form Designer mode](https://ej2.syncfusion.com/react/documentation/api/pdfviewer/formdesigner) is enabled in the Syncfusion [React PDF Viewer](https://help.syncfusion.com/document-processing/pdf/pdf-viewer/react/overview), a default [Form Designer user interface (UI)](https://document.syncfusion.com/demos/pdf-viewer/react/#/tailwind3/pdfviewer/form-designer) is displayed. This UI provides a built in toolbar for adding common form fields such as text boxes, check boxes, radio buttons, drop down lists, and signature fields. Users can place fields on the PDF, select them, resize or move them, and configure their properties using the available editing options, enabling interactive form creation directly within the viewer. - -![FormDesigner](../../javascript-es6/images/FormDesigner.gif) - -{% previewsample "/document-processing/code-snippet/pdfviewer/javascript-es6/prefilledforms-cs1" %} - -For more information about creating and editing form fields in the PDF Viewer, refer to the [Form Creation](./manage-form-fields/create-form-fields) in React PDF Viewer documentation. - -## Form Designer Toolbar +### Form Designer Toolbar The **Form Designer toolbar** appears at the top of the PDF Viewer and provides quick access to form field creation tools. It includes frequently used field types such as: @@ -97,205 +95,54 @@ The **Form Designer toolbar** appears at the top of the PDF Viewer and provides - [Signature field](../forms/manage-form-fields/create-form-fields#add-signature-field) - [Initial field](../forms/manage-form-fields/create-form-fields#add-initial-field) -Each toolbar item allows users to place the corresponding form field by selecting the tool and clicking on the desired location in the PDF document. - -![Adding a text box using the Form Designer toolbar](../../javascript-es6/images/AddTextBox.gif) - -Use the following code snippet to enable Form Designer by injecting the `FormDesigner` module. - -{% tabs %} -{% highlight js tabtitle="index.js" %} -import * as ReactDOM from 'react-dom/client'; -import * as React from 'react'; -import './index.css'; -import { PdfViewerComponent, Toolbar, Magnification, Navigation, LinkAnnotation, BookmarkView, ThumbnailView, Print, TextSelection, Annotation, TextSearch, FormFields, FormDesigner, Inject } from '@syncfusion/ej2-react-pdfviewer'; -export function App() { - return (
    -
    - - - -
    -
    ); -} -const root = ReactDOM.createRoot(document.getElementById('sample')); -root.render(); -{% endhighlight %} -{% endtabs %} - -For more information about creating and editing form fields in the PDF Viewer, refer to the [Form Creation in React PDF Viewer documentation](./manage-form-fields/create-form-fields). +#### Show or Hide the Built-in Form Designer Toolbar -## Show or Hide the Built-in Form Designer Toolbar +The visibility of the Form Designer toolbar is controlled by the [isFormDesignerToolbarVisible()](https://ej2.syncfusion.com/documentation/api/pdfviewer/index-default#isformdesignertoolbarvisible) method. This method enables the application to display or hide the Form Designer tools based on requirements. Refer to the code example [here](../toolbar-customization/form-designer-toolbar#2-show-or-hide-form-designer-toolbar-at-runtime). -You can control the visibility of the Form Designer toolbar using the [isFormDesignerToolbarVisible()](https://ej2.syncfusion.com/documentation/api/pdfviewer/index-default#isformdesignertoolbarvisible) method. This allows you to display or hide the Form Designer tools in the PDF Viewer based on your application requirements. - -**Use this method to:** -- Show the Form Designer toolbar when form design is required -- Hide the toolbar to provide cleaner viewing experience - -{% tabs %} -{% highlight js tabtitle="index.js" %} -import * as ReactDOM from 'react-dom/client'; -import * as React from 'react'; -import './index.css'; +- The Form Designer toolbar is shown when form design is required. +- The toolbar can be hidden to provide a cleaner viewing experience. -import { - PdfViewerComponent, - Toolbar, - Magnification, - Navigation, - Annotation, - LinkAnnotation, - ThumbnailView, - BookmarkView, - TextSelection, - TextSearch, - FormFields, - FormDesigner, - Inject -} from '@syncfusion/ej2-react-pdfviewer'; - -function App() { - const viewerRef = React.useRef(null); - - // Show Form Designer Toolbar - const handleShowDesigner = () => { - const viewer = viewerRef.current; - if (viewer) viewer.isFormDesignerToolbarVisible = true; - }; - - // Hide Form Designer Toolbar - const handleHideDesigner = () => { - const viewer = viewerRef.current; - if (viewer) viewer.isFormDesignerToolbarVisible = false; - }; - - return ( -
    -
    - - -
    - - - - -
    - ); -} +#### Customize the Built-in Form Designer Toolbar -const root = ReactDOM.createRoot(document.getElementById('sample')); -root.render(); -{% endhighlight %} -{% endtabs %} +The Form Designer toolbar can be customized by specifying the tools to display and arranging them in the required order using the [FormDesignerToolbarItems](https://ej2.syncfusion.com/react/documentation/api/pdfviewer/formdesignertoolbaritem) property. -## Customize the Built-in Form Designer Toolbar - -You can customize the Form Designer toolbar by specifying the tools to display and arranging them in the required order using the [FormDesignerToolbarItems](https://ej2.syncfusion.com/react/documentation/api/pdfviewer/formdesignertoolbaritem) property. - -This customization helps you limit the available tools and simplify the user interface. +This customization helps limit the available tools and simplify the user interface. A code example is available [here](../toolbar-customization/form-designer-toolbar#3-show-or-hide-form-designer-toolbar-items). **Key Points** -- Include only the toolbar items you need, in the exact order you specify. +- Only the toolbar items listed are included, in the exact order specified. - Any toolbar items not listed remain hidden, resulting in a cleaner and more focused UI. -{% tabs %} -{% highlight js tabtitle="index.js" %} -import * as ReactDOM from 'react-dom/client'; -import * as React from 'react'; -import './index.css'; -import { - PdfViewerComponent, - Toolbar, Magnification, Navigation, LinkAnnotation, BookmarkView, ThumbnailView, - Print, TextSelection, Annotation, TextSearch, FormFields, FormDesigner, Inject -} from '@syncfusion/ej2-react-pdfviewer'; +### Adding Form Fields -export function App() { - return ( -
    -
    - - - -
    -
    - ); -} +Each toolbar item in form designer toolbar allows users to place the corresponding form field by selecting the tool and clicking on the desired location in the PDF document. -const root = ReactDOM.createRoot(document.getElementById('sample')); -root.render(); -{% endhighlight %} -{% endtabs %} +![Adding a text box using the Form Designer toolbar](../../javascript-es6/images/AddTextBox.gif) -## Move, Resize, and Edit Form Fields +For more information about creating form fields in the PDF Viewer, refer to the [Form Creation in React PDF Viewer documentation](./manage-form-fields/create-form-fields#create-form-fields-using-the-form-designer-ui). -You can move, resize, and edit an existing form field directly in the PDF Viewer using the Form Designer. +### Move, Resize, and Edit Form Fields -- Move a field by selecting it and dragging it to the required position. +Fields can be moved, resized, and edited directly in the PDF Viewer using the Form Designer. -- Resize a field using the handles displayed on the field boundary. +- A field is moved by selecting it and dragging it to the required position. + +- Fields are resized using the handles displayed on the field boundary. ![Moveing and Resizing a form field](../../javascript-es6/images/move-resize-forms.gif) -- Edit a field by selecting it to open the Form Field Properties popover. The popover allows you to modify the form field and widget annotation properties. Changes are reflected immediately in the viewer and are saved when the properties popover is closed. +- Selecting a field opens the Form Field Properties popover, which allows modification of the form field and widget annotation properties. Changes are reflected immediately in the viewer and are saved when the properties popover is closed. For more information, see Editing Form Fields -## Deleting Form Fields +### Edit Form Field properties + +The **Properties** panel lets you customize the styles of form fields. Open the panel by selecting the **Properties** option in a field's context menu. + +![Textbox style from UI showing font, color, and border settings](../../javascript-es6/images/ui-textbox-style.png) + +### Deleting Form Fields -You can remove a form field from the PDF document by selecting the field and using one of the following methods: -- Click the `Delete option` in the Form Designer UI. -- Press the `Delete key` on the keyboard after selecting the form field. +A form field is removed by selecting it and either clicking the `Delete` option in the Form Designer UI or pressing the `Delete` key on the keyboard. The selected form field and its associated widget annotation are permanently removed from the page. -The selected form field and its associated widget annotation are permanently removed from the page. For more information, see [Deleting Form Fields](./manage-form-fields/remove-form-fields) ## See Also diff --git a/Document-Processing/PDF/PDF-Viewer/react/forms/form-field-events.md b/Document-Processing/PDF/PDF-Viewer/react/forms/form-field-events.md index cb3c1f10a0..71a7ed264b 100644 --- a/Document-Processing/PDF/PDF-Viewer/react/forms/form-field-events.md +++ b/Document-Processing/PDF/PDF-Viewer/react/forms/form-field-events.md @@ -10,41 +10,31 @@ domainurl: ##DomainURL## # PDF Viewer Form Field Events in React -The Syncfusion React PDF Viewer exposes form field events that let developers track user interactions, respond to changes, and implement business logic. These events support validation, UI updates, logging, and workflow automation. Form field events occur when fields are added, selected, edited, moved, resized, or removed. +The Syncfusion React PDF Viewer provides a set of form field events that report changes associated with creating, selecting, modifying, moving, resizing, or removing form fields. These events supply metadata related to the affected field and are raised during user interaction or programmatic updates. -The example below shows wiring of form-field events and a validation handler that prevents print/download when required fields are missing. +Validation‑related events are emitted when the viewer performs operations that require confirmation of field completion, such as print or download actions. ## Supported PDF Form Field Events The following table lists all supported form field events and their descriptions: -| Form Field events | Description | -|---|---| -| [formFieldAdd](https://ej2.syncfusion.com/react/documentation/api/pdfviewer/formFieldAddArgs) | Triggered when a new form field is added, either through the Form Designer UI or programmatically. | -| [formFieldClick](https://ej2.syncfusion.com/react/documentation/api/pdfviewer/formFieldClickArgs) | Fired when a form field is clicked in the viewer. | -| [formFieldDoubleClick](https://ej2.syncfusion.com/react/documentation/api/pdfviewer/formFieldDoubleClickArgs) | Fired when a form field is double clicked. | -| [formFieldFocusOut](https://ej2.syncfusion.com/react/documentation/api/pdfviewer/formFieldFocusOutEventArgs) | Triggered when a form field loses focus after editing. | -| [formFieldMouseLeave](https://ej2.syncfusion.com/react/documentation/api/pdfviewer/formFieldMouseLeaveArgs) | Fired when the mouse pointer leaves a form field. | -| [formFieldMouseOver](https://ej2.syncfusion.com/react/documentation/api/pdfviewer/formFieldMouseoverArgs) | Fired when the mouse pointer moves over a form field. | -| [formFieldMove](https://ej2.syncfusion.com/react/documentation/api/pdfviewer/formFieldMoveArgs) | Triggered when a form field is moved to a new position. | -| [formFieldPropertiesChange](https://ej2.syncfusion.com/react/documentation/api/pdfviewer/formFieldPropertiesChangeArgs) | Fired when any form field property changes, such as font, color, or constraint values. | -| [formFieldRemove](https://ej2.syncfusion.com/react/documentation/api/pdfviewer/formFieldRemoveArgs) | Triggered when a form field is deleted from the document. | -| [formFieldResize](https://ej2.syncfusion.com/react/documentation/api/pdfviewer/formFieldResizeArgs) | Fired when a form field is resized. | -| [formFieldSelect](https://ej2.syncfusion.com/react/documentation/api/pdfviewer/formFieldSelectArgs) | Fired when a form field is selected in the Form Designer. | -| [formFieldUnselect](https://ej2.syncfusion.com/react/documentation/api/pdfviewer/formFieldUnselectArgs) | Fired when a previously selected form field is unselected. | -| [validateFormFields](https://ej2.syncfusion.com/react/documentation/api/pdfviewer/validateFormFieldsArgs) | Fired when form field validation fails during print or download actions. | - -**Common Use Cases** - -Form field events can be used to: -- Validate form data before printing or downloading -- Track user interaction with form fields -- Update UI elements dynamically -- Log form changes for auditing -- Trigger workflow actions based on field changes -- Enforce business rules during form editing - -## Handle PDF Form Field Events +| Form Field events | Description | Arguments | +|---|---|---| +| [`formFieldAdd`](https://ej2.syncfusion.com/react/documentation/api/pdfviewer#formfieldadd) | Triggered when a new form field is added, either through the Form Designer UI or programmatically. | [`formFieldAddArgs`](https://ej2.syncfusion.com/react/documentation/api/pdfviewer/formFieldAddArgs) | +| [`formFieldClick`](https://ej2.syncfusion.com/react/documentation/api/pdfviewer#formfieldclick) | Fired when a form field is clicked in the viewer. | [`formFieldClickArgs`](https://ej2.syncfusion.com/react/documentation/api/pdfviewer/formFieldClickArgs) | +| [`formFieldDoubleClick`](https://ej2.syncfusion.com/react/documentation/api/pdfviewer#formfielddoubleclick) | Fired when a form field is double clicked. | [`formFieldDoubleClickArgs`](https://ej2.syncfusion.com/react/documentation/api/pdfviewer/formFieldDoubleClickArgs) | +| [`formFieldFocusOut`](https://ej2.syncfusion.com/react/documentation/api/pdfviewer#formfieldfocusout) | Triggered when a form field loses focus after editing. | [`formFieldFocusOutEventArgs`](https://ej2.syncfusion.com/react/documentation/api/pdfviewer/formFieldFocusOutEventArgs) | +| [`formFieldMouseLeave`](https://ej2.syncfusion.com/react/documentation/api/pdfviewer#formfieldmouseleave) | Fired when the mouse pointer leaves a form field. | [`formFieldMouseLeaveArgs`](https://ej2.syncfusion.com/react/documentation/api/pdfviewer/formFieldMouseLeaveArgs) | +| [`formFieldMouseOver`](https://ej2.syncfusion.com/react/documentation/api/pdfviewer#formfieldmouseover) | Fired when the mouse pointer moves over a form field. | [`formFieldMouseOverArgs`](https://ej2.syncfusion.com/react/documentation/api/pdfviewer/formFieldMouseoverArgs) | +| [`formFieldMove`](https://ej2.syncfusion.com/react/documentation/api/pdfviewer#formfieldmove) | Triggered when a form field is moved to a new position. | [`formFieldMoveArgs`](https://ej2.syncfusion.com/react/documentation/api/pdfviewer#formfieldmove) | +| [`formFieldPropertiesChange`](https://ej2.syncfusion.com/react/documentation/api/pdfviewer#formfieldpropertieschange) | Fired when any form field property changes, such as font, color, or constraint values. | [`formFieldPropertiesChangeArgs`](https://ej2.syncfusion.com/react/documentation/api/pdfviewer/formFieldPropertiesChangeArgs) | +| [`formFieldRemove`](https://ej2.syncfusion.com/react/documentation/api/pdfviewer#formfieldremove) | Triggered when a form field is deleted from the document. | [`formFieldRemoveArgs`](https://ej2.syncfusion.com/react/documentation/api/pdfviewer/formFieldRemoveArgs) | +| [`formFieldResize`](https://ej2.syncfusion.com/react/documentation/api/pdfviewer#formfieldresize) | Fired when a form field is resized. | [`formFieldResizeArgs`](https://ej2.syncfusion.com/react/documentation/api/pdfviewer/formFieldResizeArgs) | +| [`formFieldSelect`](https://ej2.syncfusion.com/react/documentation/api/pdfviewer#formfieldselect) | Fired when a form field is selected in the Form Designer. | [`formFieldSelectArgs`](https://ej2.syncfusion.com/react/documentation/api/pdfviewer/formFieldSelectArgs) | +| [`formFieldUnselect`](https://ej2.syncfusion.com/react/documentation/api/pdfviewer#formfieldunselect) | Fired when a previously selected form field is unselected. | [`formFieldUnselectArgs`](https://ej2.syncfusion.com/react/documentation/api/pdfviewer/formFieldUnselectArgs) | +| [`validateFormFields`](https://ej2.syncfusion.com/react/documentation/api/pdfviewer#validateformfields) | Fired when form field validation fails during print or download actions. | [`validateFormFieldsArgs`](https://ej2.syncfusion.com/react/documentation/api/pdfviewer/validateFormFieldsArgs) | + +## Example You can wire up form field events on the PDF Viewer instance to execute custom logic when specific actions occur. diff --git a/Document-Processing/PDF/PDF-Viewer/react/forms/form-filling.md b/Document-Processing/PDF/PDF-Viewer/react/forms/form-filling.md index 557e70cf9e..e33900cb35 100644 --- a/Document-Processing/PDF/PDF-Viewer/react/forms/form-filling.md +++ b/Document-Processing/PDF/PDF-Viewer/react/forms/form-filling.md @@ -8,331 +8,242 @@ documentation: ug domainurl: ##DomainURL## --- -# Filling PDF Forms in React PDF Viewer +# Fill PDF form fields in React PDF Viewer -The Syncfusion PDF Viewer supports three types of form-filling: +This guide shows how to update, import, and validate PDF form fields in the React PDF Viewer so you can pre-fill forms or accept user input. -1. [Filling Form Fields Programmatically](#fill-pdf-forms-programmatically) +**Outcome** Programmatically set field values, allow UI-driven filling, import form data, and validate fields on submit. - You can fill or update PDF form fields programmatically using the [updateFormFieldsValue](https://ej2.syncfusion.com/react/documentation/api/pdfviewer/index-default#updateformfieldsvalue) APIs. This approach is useful when form data needs to be set dynamically based on application logic. +## Steps to fill forms -2. [Form Filling Through User Interface](#fill-pdf-forms-through-the-user-interface) +### 1. Fill form fields programmatically - Users can fill in PDF form fields directly through the PDF Viewer user interface by typing text, selecting options, or interacting with supported form elements. +Update form field values programmatically with [`updateFormFieldsValue`](https://ej2.syncfusion.com/react/documentation/api/pdfviewer#updateformfieldsvalue). -3. [Importing Form Field Data](#fill-pdf-forms-through-import-data) - -The PDF Viewer allows importing form field data into an existing PDF document. This enables pre-filled forms using external data sources. - -## Fill PDF forms programmatically - -You can update the values of PDF form fields programmatically using the [updateFormFieldsValue](https://ej2.syncfusion.com/react/documentation/api/pdfviewer/index-default#updateformfieldsvalue) API. This method allows you to set or modify form field values dynamically based on application logic, without user interaction. - -The following example demonstrates how to update PDF form field values programmatically: +Use the example below as a complete, runnable example for a small React app. It retrieves form fields and updates a named field or the first available field. {% tabs %} -{% highlight js tabtitle="index.js" %} -import * as ReactDOM from 'react-dom/client'; -import * as React from 'react'; -import './index.css'; - +{% highlight ts tabtitle="App.tsx" %} +{% raw %} +import { RefObject, useRef } from 'react'; import { - PdfViewerComponent, - Toolbar, - Magnification, - Navigation, - LinkAnnotation, - BookmarkView, - ThumbnailView, - Print, - TextSelection, - TextSearch, - Annotation, - FormFields, - Inject, + PdfViewerComponent, Toolbar, Magnification, Navigation, LinkAnnotation, BookmarkView, + ThumbnailView, Print, TextSelection, TextSearch, Annotation, FormFields, Inject, + FormDesigner, PageOrganizer } from '@syncfusion/ej2-react-pdfviewer'; -function App() { - const viewerRef = React.useRef(null); - - const handleFillForm = () => { - const viewer = viewerRef.current; - if (!viewer) return; - - // Retrieve form fields from the viewer - const fields = - (viewer.retrieveFormFields && viewer.retrieveFormFields()) || - viewer.formFieldCollection || - []; - - // Find by name or fallback to the first field - const field = fields.find((f) => f && f.name === 'name') || fields[0]; - - if (field) { - field.value = 'John Doe'; - field.tooltip = 'First'; - // Push changes to viewer - viewer.updateFormFieldsValue(field); - } else { - console.warn('No form fields available to update.'); - } - }; - - return ( -
    -
    - -
    - -
    - - - -
    -
    - ); +export default function App() { + const viewerRef: RefObject = useRef(null); + + const handleFillForm = () => { + const viewer = viewerRef.current; + if (!viewer) return; + + // Retrieve form fields from the viewer + const fields = + (viewer.retrieveFormFields && viewer.retrieveFormFields()) || + viewer.formFieldCollections || + []; + // Find by name or fallback to the first field + const field = fields.find((f) => f && f.name === 'name') || fields[0]; + + if (field) { + field.value = 'John Doe'; + field.tooltip = 'First'; + // Push changes to viewer + viewer.updateFormFieldsValue(field); + } else { + console.warn('No form fields available to update.'); + } + }; + + return ( +
    +
    + +
    + +
    + + + +
    +
    + ); } - -const root = ReactDOM.createRoot(document.getElementById('sample')); -root.render(); +{% endraw %} {% endhighlight %} {% endtabs %} -## Fill PDF forms through the User Interface +**Expected result:** Clicking the *Fill Form Fields* button sets the first or named field's value to *John Doe* in the viewer. -The Syncfusion PDF Viewer allows users to fill PDF form fields directly through the user interface without using code. Users can click on form fields and enter or select values based on the field type. +### 2. Fill form fields via UI -![Form Filling](../../javascript-es6/images/FormFields.gif) +Users can click form controls and enter/select values. Supported field types include textboxes, checkboxes, radio buttons, dropdowns, list boxes, and signature fields. Edits are retained during the viewing session. -The PDF Viewer supports common form fields such as text boxes, check boxes, radio buttons, drop-down lists, list boxes, and signature fields. Filled values can be edited at any time, and the entered data is retained during the viewing session. +![Form Filling](../../javascript-es6/images/FormFields.gif) {% previewsample "/document-processing/code-snippet/pdfviewer/javascript-es6/prefilledforms-cs1" %} -## Fill PDF forms through Import Data +### 3. Fill form fields through imported data -The Syncfusion PDF Viewer allows you to import form field data into an existing PDF document using the [importFormFields](https://ej2.syncfusion.com/react/documentation/api/pdfviewer/index-default#importformfields) API. This feature enables you to pre-fill form fields using data from an external source without requiring manual user input. - -Imported form field data is automatically mapped to the corresponding form fields in the PDF document based on the field names. Once the data is imported, the populated values are displayed in the PDF Viewer and can be edited through the user interface if required. +Use [`importFormFields`](https://ej2.syncfusion.com/react/documentation/api/pdfviewer#importformfields) to map external data into PDF fields by name. The example below shows how to trigger import from a button handler. {% tabs %} -{% highlight js tabtitle="index.js" %} -import * as ReactDOM from 'react-dom/client'; -import * as React from 'react'; -import './index.css'; - +{% highlight ts tabtitle="App.tsx" %} +{% raw %} +import { RefObject, useRef } from 'react'; import { - PdfViewerComponent, - Toolbar, - Magnification, - Navigation, - Annotation, - LinkAnnotation, - ThumbnailView, - BookmarkView, - TextSelection, - FormFields, - FormDesigner, - Inject + PdfViewerComponent, Toolbar, Magnification, Navigation, LinkAnnotation, BookmarkView, + ThumbnailView, Print, TextSelection, TextSearch, Annotation, FormFields, Inject, + FormDesigner, PageOrganizer, FormFieldDataFormat } from '@syncfusion/ej2-react-pdfviewer'; -// We import the enum from the core package (not the React wrapper) -import { FormFieldDataFormat } from '@syncfusion/ej2-pdfviewer'; - -function App() { - const viewerRef = React.useRef(null); - - const handleImportJson = () => { - const viewer = viewerRef.current; - if (!viewer) return; - - // NOTE: - // The first parameter can be: - // - a file path/url (if accessible from the client), - // - or a File/Blob stream from an in real apps. - // Replace 'File' with your actual file or path as per your integration. - viewer.importFormFields('File', FormFieldDataFormat.Json); - }; - - return ( -
    -
    - -
    - -
    - - - -
    -
    - ); +export default function App() { + const viewerRef: RefObject = useRef(null); + + const handleImportJson = () => { + const viewer = viewerRef.current; + if (!viewer) return; + // NOTE: + // The first parameter can be: + // - a file path/url (in server mode), + // - or a base64 encoded File/Blob stream from an in real apps. + // Replace 'File' with your actual file or path as per your integration. + viewer.importFormFields('File', FormFieldDataFormat.Json); + }; + + return ( +
    +
    + +
    + +
    + + + +
    +
    + ); } - -const root = ReactDOM.createRoot(document.getElementById('sample')); -root.render(); +{% endraw %} {% endhighlight %} {% endtabs %} For more details, see [Import Form Data](./import-export-form-fields/import-form-fields). -## How to get the filled data and store it to a backing system - -You can export the filled form field data from the PDF Viewer and store it in a backend system such as a database or file storage. The exported data can later be imported to restore the form state. - -For more details, see [Export Form Data](./import-export-form-fields/export-form-fields). - -## How to Validate Form Fields using `validateFormFields` Event +### 4. Validate form fields on submit -The [validateFormFields](https://ej2.syncfusion.com/react/documentation/api/pdfviewer/index-default#validateformfields) event in the Syncfusion PDF Viewer is triggered when a user tries to download or submit a form while validation is enabled. You can use the [retrieveFormFields()](https://ej2.syncfusion.com/react/documentation/api/pdfviewer/index-default#validateformfields) API to get all the form fields and check them one by one to see if any form fields values are empty. - -This validation applies to all form field types in the PDF Viewer. A textbox is empty if no text is entered, a list box or dropdown is empty if no item is selected, a signature or initial field is empty if the user has not signed, and radio buttons or checkboxes are empty if none are chosen. -By enabling [enableFormFieldsValidation](https://ej2.syncfusion.com/react/documentation/api/pdfviewer/index-default#enableformfieldsvalidation) and wiring the event, you can go through each field and stop the action if required fields are not filled. +Enable [`enableFormFieldsValidation`](https://ej2.syncfusion.com/react/documentation/api/pdfviewer#enableformfieldsvalidation) and handle [`validateFormFields`](https://ej2.syncfusion.com/react/documentation/api/pdfviewer#validateformfields) to check required fields and cancel submission when necessary. Example below shows adding required fields via [`formDesignerModule`](https://ej2.syncfusion.com/react/documentation/api/pdfviewer/formdesigner) and validating them. {% tabs %} {% highlight js tabtitle="index.js" %} -import * as ReactDOM from 'react-dom/client'; -import * as React from 'react'; -import './index.css'; - +{% raw %} +import { RefObject, useRef } from 'react'; import { - PdfViewerComponent, - Toolbar, - Magnification, - Navigation, - LinkAnnotation, - ThumbnailView, - BookmarkView, - TextSelection, - Annotation, - FormDesigner, - FormFields, - Inject, + PdfViewerComponent, Toolbar, Magnification, Navigation, LinkAnnotation, + ThumbnailView, BookmarkView, TextSelection, Annotation, FormDesigner, FormFields, + Inject, TextFieldSettings } from '@syncfusion/ej2-react-pdfviewer'; -function App() { - const viewerRef = React.useRef(null); - - // Runs after the document is loaded into the viewer - const handleDocumentLoad = () => { - const viewer = viewerRef.current; - if (!viewer) return; - - // Add a required Email field - viewer.formDesignerModule.addFormField('Textbox', { - name: 'Email', - bounds: { X: 146, Y: 260, Width: 220, Height: 24 }, - isRequired: true, - tooltip: 'Email is required', - }); - - // Add a required Phone field - viewer.formDesignerModule.addFormField('Textbox', { - name: 'Phone', - bounds: { X: 146, Y: 300, Width: 220, Height: 24 }, - isRequired: true, - tooltip: 'Phone number is required', - }); - }; - - // Validates only the added fields on form submit/validate trigger - const handleValidateFormFields = (args) => { - const viewer = viewerRef.current; - if (!viewer) return; - - const fields = viewer.retrieveFormFields ? viewer.retrieveFormFields() : []; - - fields.forEach((field) => { - if ((field.name === 'Email' || field.name === 'Phone') && !field.value) { - alert(field.name + ' field cannot be empty.'); - args.isFormSubmitCancelled = true; - } - }); - }; - - return ( -
    - - - -
    - ); +export default function App() { + const viewerRef: RefObject = useRef(null); + + // Runs after the document is loaded into the viewer + const handleDocumentLoad = () => { + const viewer = viewerRef.current; + if (!viewer) return; + + // Add a required Email field + viewer.formDesignerModule.addFormField('Textbox', { + name: 'Email', + bounds: { X: 146, Y: 260, Width: 220, Height: 24 }, + isRequired: true, + tooltip: 'Email is required', + } as TextFieldSettings); + + // Add a required Phone field + viewer.formDesignerModule.addFormField('Textbox', { + name: 'Phone', + bounds: { X: 146, Y: 300, Width: 220, Height: 24 }, + isRequired: true, + tooltip: 'Phone number is required', + } as TextFieldSettings); + }; + + // Validates only the added fields on form submit/validate trigger + const handleValidateFormFields = () => { + const viewer = viewerRef.current; + if (!viewer) return; + + const fields = viewer.retrieveFormFields ? viewer.retrieveFormFields() : []; + + fields.forEach((field) => { + if ((field.name === 'Email' || field.name === 'Phone') && !field.value) { + alert(field.name + ' field cannot be empty.'); + } + }); + }; + + return ( +
    + + + +
    + ); } - -const root = ReactDOM.createRoot(document.getElementById('sample')); -root.render(); +{% endraw %} {% endhighlight %} {% endtabs %} +## Troubleshooting + +- If fields are not editable, confirm `FormFields` module is injected into PDF Viewer. +- If examples fail to load, verify your [`resourceUrl`](https://helpej2.syncfusion.com/react/documentation/api/pdfviewer#resourceurl) matches the installed PDF Viewer version. +- For import issues, ensure JSON keys match the PDF field `name` values. + ## See also - [Form Designer overview](./overview) diff --git a/Document-Processing/PDF/PDF-Viewer/react/forms/import-export-form-fields/export-form-fields.md b/Document-Processing/PDF/PDF-Viewer/react/forms/import-export-form-fields/export-form-fields.md index 5214335817..3371cc992e 100644 --- a/Document-Processing/PDF/PDF-Viewer/react/forms/import-export-form-fields/export-form-fields.md +++ b/Document-Processing/PDF/PDF-Viewer/react/forms/import-export-form-fields/export-form-fields.md @@ -9,194 +9,132 @@ documentation: ug # Export PDF Form Data from React PDF Viewer -The PDF Viewer allows you to export form field data in multiple formats for easy storage or integration. Supported formats: +This guide shows concise, actionable steps to export PDF form field data for storage or integration. It covers: -- [FDF](#export-as-fdf) -- [XFDF](#export-as-xfdf) -- [JSON](#export-as-json) -- [JavaScript Object](#export-as-object) (for custom persistence) +- Exporting as [FDF](#3-export-as-fdf), [XFDF](#4-export-as-xfdf), and [JSON](#5-export-as-json) using [`exportFormFields()`](https://ej2.syncfusion.com/react/documentation/api/pdfviewer#exportformfields). +- Exporting as a [JavaScript object](#6-export-as-a-javascript-object) using [`exportFormFieldsAsObject()`](https://ej2.syncfusion.com/react/documentation/api/pdfviewer#exportformfieldsasobject). -## Available methods +## Steps -- [exportFormFields](https://ej2.syncfusion.com/react/documentation/api/pdfviewer/index-default#exportformfields)(destination?, format) — Exports data to a file in the specified format. -- [exportFormFieldsAsObject](https://ej2.syncfusion.com/react/documentation/api/pdfviewer/index-default#exportformfieldsasobject)(format) — Exports data as a JavaScript object for custom handling. -- [importFormFields](https://ej2.syncfusion.com/react/documentation/api/pdfviewer/index-default#importformfields)(sourceOrObject, format) — Import data back into the PDF. +### 1. Configure the PDF Viewer -## How to export +Install and import the viewer with required services. -Use [exportFormFields()](https://ej2.syncfusion.com/react/documentation/api/pdfviewer/index-default#exportformfields) with an optional destination path and the format type. +{% highlight ts %} +import { + PdfViewerComponent, Toolbar, Magnification, Navigation, Annotation, LinkAnnotation, + ThumbnailView, BookmarkView, TextSelection, TextSearch, FormFields, FormDesigner, + PageOrganizer, Inject, Print, FormFieldDataFormat +} from '@syncfusion/ej2-react-pdfviewer'; +import { RefObject, useRef } from 'react'; +{% endhighlight %} -### Export as FDF -The example below exports form field data as FDF. +### 2. Initialize ref -{% tabs %} -{% highlight js tabtitle="index.js" %} -import * as ReactDOM from 'react-dom/client'; -import React, { useRef } from 'react'; -import './index.css'; -import { PdfViewerComponent, Toolbar, Magnification, Navigation, LinkAnnotation, BookmarkView, ThumbnailView, TextSelection, Annotation, FormFields, FormDesigner, Inject, FormFieldDataFormat } from '@syncfusion/ej2-react-pdfviewer'; - -function App() { - const viewerRef = useRef(null); - - const onExportFdf = () => { - // Data must be the desired path or file name for the exported document. - viewerRef.current?.exportFormFields('ExportedData', FormFieldDataFormat.Fdf); - }; - - return ( -
    - - - - -
    - ); -} +Initialize the viewer with a `ref` so you can call export methods. -const root = ReactDOM.createRoot(document.getElementById('sample')); -root.render(); +{% highlight ts %} +const viewerRef: RefObject = useRef(null); {% endhighlight %} -{% endtabs %} -### Export as XFDF -The example below exports form field data as XFDF. +### 3. Export as FDF -{% tabs %} -{% highlight js tabtitle="index.js" %} -import * as ReactDOM from 'react-dom/client'; -import React, { useRef } from 'react'; -import './index.css'; -import { PdfViewerComponent, Toolbar, Magnification, Navigation, LinkAnnotation, BookmarkView, ThumbnailView, TextSelection, Annotation, FormFields, FormDesigner, Inject, FormFieldDataFormat } from '@syncfusion/ej2-react-pdfviewer'; - -function App() { - const viewerRef = useRef(null); - - const onExportXfdf = () => { - // Data must be the desired path or file name for the exported document. - viewerRef.current?.exportFormFields('FormData', FormFieldDataFormat.Xfdf); - }; - - return ( -
    - - - - -
    - ); -} +Use [`exportFormFields(destination?, FormFieldDataFormat.Fdf)`](https://ej2.syncfusion.com/react/documentation/api/pdfviewer#exportformfields) to download an FDF file. -const root = ReactDOM.createRoot(document.getElementById('sample')); -root.render(); +{% highlight ts %} +viewerRef.current?.exportFormFields('FormData', FormFieldDataFormat.Fdf); {% endhighlight %} -{% endtabs %} -### Export as JSON -The example below exports form field data as JSON. +### 4. Export as XFDF -{% tabs %} -{% highlight js tabtitle="index.js" %} -import * as ReactDOM from 'react-dom/client'; -import React, { useRef } from 'react'; -import './index.css'; -import { PdfViewerComponent, Toolbar, Magnification, Navigation, LinkAnnotation, BookmarkView, ThumbnailView, TextSelection, Annotation, FormFields, FormDesigner, Inject, FormFieldDataFormat } from '@syncfusion/ej2-react-pdfviewer'; - -function App() { - const viewerRef = useRef(null); - - const onExportJson = () => { - // Data must be the desired path or file name for the exported document. - viewerRef.current?.exportFormFields('FormData', FormFieldDataFormat.Json); - }; - - return ( -
    - - - - -
    - ); -} +Use [`FormFieldDataFormat.Xfdf`](https://ej2.syncfusion.com/react/documentation/api/pdfviewer/formfielddataformat) to export XFDF. -const root = ReactDOM.createRoot(document.getElementById('sample')); -root.render(); +{% highlight ts %} +viewerRef.current?.exportFormFields('FormData', FormFieldDataFormat.Xfdf); {% endhighlight %} -{% endtabs %} -### Export as Object +### 5. Export as JSON -Use [exportFormFieldsAsObject()](https://ej2.syncfusion.com/react/documentation/api/pdfviewer/index-default#exportformfieldsasobject) to obtain form data as a JavaScript object for database or API integration. +Use [`FormFieldDataFormat.Json`](https://ej2.syncfusion.com/react/documentation/api/pdfviewer/formfielddataformat) to export form data as a JSON file. + +{% highlight ts %} +viewerRef.current?.exportFormFields('FormData', FormFieldDataFormat.Json); +{% endhighlight %} + +### 6. Export as a JavaScript object + +Use [`exportFormFieldsAsObject(format)`](https://ej2.syncfusion.com/react/documentation/api/pdfviewer#exportformfieldsasobject) to get data for API calls or storing in a database. + +{% highlight ts %} +const data = await viewerRef.current?.exportFormFieldsAsObject(); +{% endhighlight %} + +## Complete example + +The example below provides a single page with buttons to export in all supported formats. It uses the same imports shown above and is ready to run in a typical React app. {% tabs %} -{% highlight js tabtitle="index.js" %} -import * as ReactDOM from 'react-dom/client'; -import React, { useRef } from 'react'; -import './index.css'; -import { PdfViewerComponent, Toolbar, Magnification, Navigation, LinkAnnotation, BookmarkView, ThumbnailView, TextSelection, Annotation, FormFields, FormDesigner, Inject, FormFieldDataFormat } from '@syncfusion/ej2-react-pdfviewer'; - -function App() { - const viewerRef = useRef(null); - - const onExportObject = async () => { - const data = await viewerRef.current?.exportFormFieldsAsObject(FormFieldDataFormat.Fdf); - // Save or send to server - console.log('Exported object:', data); - - // Alternative formats: - // await viewerRef.current?.exportFormFieldsAsObject(FormFieldDataFormat.Xfdf); - // await viewerRef.current?.exportFormFieldsAsObject(FormFieldDataFormat.Json); - }; - - return ( -
    - - - - -
    - ); +{% highlight js %} +{% raw %} +import { + PdfViewerComponent, Toolbar, Magnification, Navigation, Annotation, LinkAnnotation, + ThumbnailView, BookmarkView, TextSelection, TextSearch, FormFields, FormDesigner, + PageOrganizer, Inject, Print, FormFieldDataFormat +} from '@syncfusion/ej2-react-pdfviewer'; +import { RefObject, useRef } from 'react'; + +export default function App() { + const viewerRef: RefObject = useRef(null); + + const onExportFdf = () => { + viewerRef.current?.exportFormFields('FormData', FormFieldDataFormat.Fdf); + }; + + const onExportXfdf = () => { + viewerRef.current?.exportFormFields('FormData', FormFieldDataFormat.Xfdf); + }; + + const onExportJson = () => { + viewerRef.current?.exportFormFields('FormData', FormFieldDataFormat.Json); + }; + + const onExportObject = async () => { + const data = await viewerRef.current?.exportFormFieldsAsObject(); + console.log('Exported object:', data); + }; + + return ( +
    +
    + + + + +
    + + + +
    + ); } - -const root = ReactDOM.createRoot(document.getElementById('sample')); -root.render(); +{% endraw %} {% endhighlight %} {% endtabs %} -## Common Use Cases +[View Sample on GitHub](https://github.com/SyncfusionExamples/react-pdf-viewer-examples) -- Save user-entered data to your server without altering the original PDF. -- Export as JSON for REST API integration. -- Export as FDF/XFDF for compatibility with other PDF tools. -- Export as Object to merge with app state or store securely. -- Automate exports after [validation](../form-validation) using [validateFormFields()](https://ej2.syncfusion.com/react/documentation/api/pdfviewer/index-default#validateformfields) +## Troubleshooting -[View Sample on GitHub](https://github.com/SyncfusionExamples/react-pdf-viewer-examples) +- Ensure `FormFields` and [`FormDesigner`](https://ej2.syncfusion.com/react/documentation/api/pdfviewer/formdesigner) services are injected when using form APIs. +- Confirm [`resourceUrl`](https://ej2.syncfusion.com/react/documentation/api/pdfviewer#resourceurl) points to the matching `ej2-pdfviewer-lib` version. +- If exports fail in restrictive browsers, check popup/download settings and CORS for hosted endpoints. +- For server-side persistence, use [`exportFormFieldsAsObject()`](https://ej2.syncfusion.com/react/documentation/api/pdfviewer#exportformfieldsasobject) and send the result to your API. ## See also diff --git a/Document-Processing/PDF/PDF-Viewer/react/forms/import-export-form-fields/import-form-fields.md b/Document-Processing/PDF/PDF-Viewer/react/forms/import-export-form-fields/import-form-fields.md index b86676fece..0fa5e1ff68 100644 --- a/Document-Processing/PDF/PDF-Viewer/react/forms/import-export-form-fields/import-form-fields.md +++ b/Document-Processing/PDF/PDF-Viewer/react/forms/import-export-form-fields/import-form-fields.md @@ -7,188 +7,87 @@ control: PDF Viewer documentation: ug --- -# Import PDF Form Data into React PDF Viewer +# Import PDF Form Data into the React PDF Viewer -The PDF Viewer imports values into interactive form fields in the currently loaded PDF. Supported formats: +This guide shows how to import form field values into an already loaded PDF in the EJ2 React PDF Viewer. **Supported import formats**: FDF, XFDF, JSON, and importing from a JavaScript object. -- [FDF](#import-as-fdf) -- [XFDF](#import-xfdf) -- [JSON](#import-json) +## Steps to import data -## API to use -- [importFormFields](https://ej2.syncfusion.com/react/documentation/api/pdfviewer/index-default#importformfields)(sourceOrObject, format) +1. Import the viewer, inject `FormFields` / `FormDesigner` services, and create a `ref` to call `importFormFields`. -The `sourceOrObject` parameter accepts a file path/URL or a JavaScript object with field-value pairs when importing from an object. +2. Call [`importFormFields(data, format)`](https://ej2.syncfusion.com/react/documentation/api/pdfviewer#importformfields) where `format` is one of `FormFieldDataFormat.Fdf`, `FormFieldDataFormat.Xfdf`, or `FormFieldDataFormat.Json`. `data` may be a file path (for server/file-based imports) / base64 string or a JavaScript object mapping field names to values. -N> For a server-backed viewer set the `serviceUrl` before importing so the control can forward requests to the server. +3. Verify the form fields are populated after the import completes. For server-backed imports, ensure [`serviceUrl`](https://ej2.syncfusion.com/react/documentation/api/pdfviewer#serviceurl) is configured and the import file is accessible by the server. -### Import FDF +## Example -{% tabs %} -{% highlight js tabtitle="index.js" %} -import * as ReactDOM from 'react-dom/client'; -import React, { useRef } from 'react'; -import './index.css'; -import { - PdfViewerComponent, - Toolbar, - Magnification, - Navigation, - Annotation, - LinkAnnotation, - ThumbnailView, - BookmarkView, - TextSelection, - FormFields, - FormDesigner, - Inject, - FormFieldDataFormat -} from '@syncfusion/ej2-react-pdfviewer'; - -function App() { - const viewerRef = useRef(null); - - const importFdf = () => { - // The file for importing should be accessible at the given path or as a file stream depending on your integration - viewerRef.current?.importFormFields('File', FormFieldDataFormat.Fdf); - }; - - return ( -
    - - - - -
    - ); -} - -const root = ReactDOM.createRoot(document.getElementById('sample')); -root.render(); -{% endhighlight %} -{% endtabs %} - -### Import XFDF - -{% tabs %} -{% highlight js tabtitle="index.js" %} -import * as ReactDOM from 'react-dom/client'; -import React, { useRef } from 'react'; -import './index.css'; -import { - PdfViewerComponent, - Toolbar, - Magnification, - Navigation, - Annotation, - LinkAnnotation, - ThumbnailView, - BookmarkView, - TextSelection, - FormFields, - FormDesigner, - Inject, - FormFieldDataFormat -} from '@syncfusion/ej2-react-pdfviewer'; - -function App() { - const viewerRef = useRef(null); - - const importXfdf = () => { - // The file for importing should be accessible at the given path or as a file stream depending on your integration - viewerRef.current?.importFormFields('File', FormFieldDataFormat.Xfdf); - }; - - return ( -
    - - - - -
    - ); -} - -const root = ReactDOM.createRoot(document.getElementById('sample')); -root.render(); -{% endhighlight %} -{% endtabs %} - -### Import JSON +The example below provides a minimal React app with four buttons to import FDF, XFDF, JSON, or an object. Replace the import file identifiers (`'File'`) with your file path or implement a file upload to pass a Blob/stream. {% tabs %} {% highlight js tabtitle="index.js" %} -import * as ReactDOM from 'react-dom/client'; -import React, { useRef } from 'react'; -import './index.css'; +{% raw %} +import { RefObject, useRef } from 'react'; import { - PdfViewerComponent, - Toolbar, - Magnification, - Navigation, - Annotation, - LinkAnnotation, - ThumbnailView, - BookmarkView, - TextSelection, - FormFields, - FormDesigner, - Inject, - FormFieldDataFormat + PdfViewerComponent, Toolbar, Magnification, Navigation, Annotation, LinkAnnotation, + ThumbnailView, BookmarkView, TextSelection, FormFields, FormDesigner, Inject, + PageOrganizer, Print, FormFieldDataFormat } from '@syncfusion/ej2-react-pdfviewer'; -function App() { - const viewerRef = useRef(null); - - const importJson = () => { - // The file for importing should be accessible at the given path or as a file stream depending on your integration - viewerRef.current?.importFormFields('File', FormFieldDataFormat.Json); - }; - - return ( -
    - - - - -
    - ); +export default function App() { + const viewerRef: RefObject = useRef(null); + + // The file for importing should be accessible at the given path or as a base 64 string depending on your integration + const importFdf = () => viewerRef.current?.importFormFields('File', FormFieldDataFormat.Fdf); + const importXfdf = () => viewerRef.current?.importFormFields('File', FormFieldDataFormat.Xfdf); + const importJson = () => viewerRef.current?.importFormFields('File', FormFieldDataFormat.Json); + // Import from a JavaScript object (fieldName: value) + const importFromObject = () => { + const formDataObject = { + 'fullname': 'Jane Doe', + 'email': 'jane.doe@example.com', + 'agreeTerms': 'yes' + }; + viewerRef.current?.importFormFields(JSON.stringify(formDataObject), FormFieldDataFormat.Json); + }; + + return ( +
    +
    + + + + +
    + + + + +
    + ); } - -const root = ReactDOM.createRoot(document.getElementById('sample')); -root.render(); +{% endraw %} {% endhighlight %} {% endtabs %} -## Common Use Cases +**Expected result**: The loaded PDF's interactive form fields are populated with the values from the imported file/object. For object imports, fields matching the object keys receive the provided values. -- Pre-fill application forms from a database using JSON. -- Migrate data from other PDF tools using FDF/XFDF. -- Restore user progress saved locally or on the server. -- Combine with validation to block print/download until required fields are completed. +## Troubleshooting -[View Sample on GitHub](https://github.com/SyncfusionExamples/react-pdf-viewer-examples) +- If imports do not populate fields, confirm the field names in the source match the PDF form field names. +- For file-based imports, ensure you use server mode and that the import file is accessible to the viewer. +- If using a Blob, pass the encoded base64 string of Blob/stream instead of the string `'File'`. +- Check browser console for network errors when the viewer attempts to fetch import files. ## See also diff --git a/Document-Processing/PDF/PDF-Viewer/react/forms/manage-form-fields/create-form-fields.md b/Document-Processing/PDF/PDF-Viewer/react/forms/manage-form-fields/create-form-fields.md index a1e2e20b1e..c97494df3d 100644 --- a/Document-Processing/PDF/PDF-Viewer/react/forms/manage-form-fields/create-form-fields.md +++ b/Document-Processing/PDF/PDF-Viewer/react/forms/manage-form-fields/create-form-fields.md @@ -9,24 +9,30 @@ documentation: ug # Create PDF Form Fields in React -Create or add new form fields visually using the [Form Designer UI](https://document.syncfusion.com/demos/pdf-viewer/react/#/tailwind3/pdfviewer/form-designer) or programmatically using the API. +Create or add new form fields visually with the Form Designer UI or programmatically using the React PDF Viewer API. This guide explains both methods and shows field‑specific examples and a complete runnable example. -## Create Form Fields Using the Form Designer UI -Use this approach when you want to design forms manually without writing code. +**Outcome:** -**Steps:** +The guide explains the following: +- How to add fields with the Form Designer UI. +- How to add and edit fields programmatically (API). +- How to add common field types: Textbox, Password, CheckBox, RadioButton, ListBox, DropDown, Signature, Initial. -1. Enable [Form Designer](../form-designer) mode in the PDF Viewer. -2. Click a form field type (Textbox, Checkbox, Dropdown, etc.) from the toolbar. -3. Click on the PDF page to place the form field. -4. Move or resize the field as required. -5. Configure field properties using the **Properties** panel. +## Steps + +### 1. Create form fields using Form Designer UI. + +- Enable the Form Designer mode in the PDF Viewer. See [Form Designer overview](../overview). +- Select a field type from the toolbar and click the PDF page to place it. +- Move/resize the field and configure properties in the **Properties** panel. ![Adding a form field using the Form Designer UI](../../../javascript-es6/images/FormDesigner.gif) -## Add Form Fields Programmatically (API) +### 2. Create Form fields programmatically + +Use [`addFormField`](https://ej2.syncfusion.com/react/documentation/api/pdfviewer/formdesigner#addformfield) method of the [formDesigner](https://ej2.syncfusion.com/react/documentation/api/pdfviewer/formdesigner) module inside the viewer's [`documentLoad`](https://ej2.syncfusion.com/react/documentation/api/pdfviewer#documentload) handler or in response to user actions. -Use this approach when you want to generate form fields dynamically based on data or application logic. +Use this approach to generate form fields dynamically based on data or application logic. {% tabs %} {% highlight js tabtitle="index.js" %} @@ -72,16 +78,17 @@ root.render(); - Pre-filling forms from databases - Automating form creation workflows -## PDF Form Field Types and How to Add Them -Each field can be added via the **Form Designer** or **programmatically**. +## Field‑specific instructions + +Below are concise UI steps and the programmatic examples for each common field type. The code samples below are complete per‑field examples you can reuse unchanged. ### Textbox -**Add via Toolbar (UI)** -- Open **Form Designer** → select **Textbox** → click on the page → configure in **Properties**. +**Add via UI**: Open Form Designer toolbar → select Textbox → click page → configure properties + ![Textbox properties panel](../../../javascript-es6/images/ui-textbox-edit.png) -**Add Programmatically (API)** +**Add Programmatically (API)**: {% tabs %} {% highlight js tabtitle="index.js" %} @@ -127,11 +134,11 @@ root.render(); ### Password -**Add via Toolbar (UI)** -- Select **Password** → place it → configure tooltip, required, max length. +**Add via UI**: Open form designer toolbar → Select Password → place → configure properties + ![Password Properties Panel](../../../javascript-es6/images/ui-password-edit.png) -**Add Programmatically (API)** +**Add Programmatically (API)**: {% tabs %} {% highlight js tabtitle="index.js" %} @@ -176,11 +183,12 @@ root.render(); {% endtabs %} ### CheckBox -**Add via Toolbar (UI)** -- Select **CheckBox** → click to place → duplicate for options → set isChecked, tooltip, appearance. + +**Add via UI**: Open form designer toolbar → Select CheckBox → click to place → duplicate for options. + ![CheckBox Properties Panel](../../../javascript-es6/images/ui-checkbox-edit.png) -**Add Programmatically (API)** +**Add Programmatically (API)**: {% tabs %} {% highlight js tabtitle="index.js" %} @@ -224,11 +232,12 @@ root.render(); {% endtabs %} ### RadioButton -**Add via Toolbar (UI)** -- Select **RadioButton** → place buttons with the **same Name** to group → configure selection/colors. + +**Add via UI**: Open form designer toolbar → Select RadioButton → place buttons using the same `name` to group them. + ![Radio Button Properties Panel](../../../javascript-es6/images/ui-radiobutton-edit.png) -**Add Programmatically (API)** +**Add Programmatically (API)**: {% tabs %} {% highlight js tabtitle="index.js" %} @@ -279,11 +288,12 @@ root.render(); {% endtabs %} ### ListBox -**Add via Toolbar (UI)** -- Select **ListBox** → place → add items in **Properties**. + +**Add via UI**: Open form designer toolbar → Select ListBox → place → add items in Properties. + ![ListBox Properties Panel](../../../javascript-es6/images/ui-listbox-edit.png) -**Add Programmatically (API)** +**Add Programmatically (API)**: {% tabs %} {% highlight js tabtitle="index.js" %} @@ -332,11 +342,12 @@ root.render(); {% endtabs %} ### DropDown -**Add via Toolbar (UI)** -- Select **DropDown** → place → add items → set default value. + +**Add via UI**: Open form designer toolbar → Select DropDown → place → add items → set default value. + ![DropDown Properties Panel](../../../javascript-es6/images/ui-dropdown-edit.png) -**Add Programmatically (API)** +**Add Programmatically (API)**: {% tabs %} {% highlight js tabtitle="index.js" %} @@ -384,11 +395,12 @@ root.render(); {% endtabs %} ### Signature Field -**Add via Toolbar (UI)** -- Select **Signature Field** → place where signing is required → configure indicator text, thickness, tooltip, required. + +**Add via UI**: Open form designer toolbar → select Signature Field → place where signing is required → configure indicator text/thickness/tooltip/isRequired. + ![Signature Field](../../../javascript-es6/images/ui-signature-edit.png) -**Add Programmatically (API)** +**Add Programmatically (API)**: {% tabs %} {% highlight js tabtitle="index.js" %} @@ -431,11 +443,12 @@ root.render(); {% endtabs %} ### Initial Field -**Add via Toolbar (UI)** -- Select **Initial Field** → place where initials are needed → configure text and required state. + +**Add via UI**: Open form designer toolbar → select Initial Field → place where initials are needed → configure text/isRequired. + ![Initial field Properties Panel](../../../javascript-es6/images/ui-initial-edit.png) -**Add Programmatically (API)** +**Add Programmatically (API)**: {% tabs %} {% highlight js tabtitle="index.js" %} @@ -477,11 +490,11 @@ root.render(); {% endhighlight %} {% endtabs %} -## Add Fields Dynamically with setFormFieldMode +## Add fields dynamically with setFormFieldMode -Use **setFormFieldMode()** to add fields on the fly based on user actions. +Use [`setFormFieldMode()`](https://ej2.syncfusion.com/react/documentation/api/pdfviewer/formdesigner#setformfieldmode) to switch the designer into a specific field mode and let users add fields on the fly. -### Edit Form Fields in TypeScript PDF Viewer +### Edit Form Fields in React PDF Viewer You can edit form fields using the UI or API. #### Edit Using the UI @@ -490,6 +503,7 @@ You can edit form fields using the UI or API. - Use the toolbar to toggle field mode or add new fields. #### Edit Programmatically + {% tabs %} {% highlight js tabtitle="index.js" %} import * as ReactDOM from 'react-dom/client'; @@ -556,7 +570,12 @@ root.render(); [View Sample on GitHub](https://github.com/SyncfusionExamples/react-pdf-viewer-examples) -## See Also +## Troubleshooting + +- If fields do not appear, verify [`resourceUrl`](https://ej2.syncfusion.com/react/documentation/api/pdfviewer#resourceurl) matches the EJ2 PDF Viewer library version and that the document loads correctly. +- If using WASM or additional services, confirm those resources are reachable from the environment. + +## Related topics - [Form Designer overview](../overview) - [Form Designer Toolbar](../../toolbar-customization/form-designer-toolbar) diff --git a/Document-Processing/PDF/PDF-Viewer/react/forms/read-form-field-values.md b/Document-Processing/PDF/PDF-Viewer/react/forms/read-form-field-values.md new file mode 100644 index 0000000000..d94eed5563 --- /dev/null +++ b/Document-Processing/PDF/PDF-Viewer/react/forms/read-form-field-values.md @@ -0,0 +1,106 @@ +--- +layout: post +title: Read and Extract PDF Form Field Values in React | Syncfusion +description: Learn how to read and extract values from PDF form fields in the EJ2 React PDF Viewer, including text, checkboxes, radio buttons, dropdowns, and signatures. +platform: document-processing +control: PDF Viewer +documentation: ug +domainurl: ##DomainURL## +--- + +# Read and Extract PDF Form Field Values in React PDF Viewer + +The React PDF Viewer allows you to read the values of interactive PDF form fields including textboxes, checkboxes, radio buttons, dropdowns, signatures, and more. Use the APIs below to retrieve form data programmatically for validation, submission, or syncing with your app state. + +This guide shows common patterns with concise code snippets you can copy into your React components. + +## Access the Form Field Collection + +Get all available form field data by reading viewer's `formFieldCollections`. For more information, see [`formFieldCollections`](./form-fields-api#formfieldcollections). + +```ts +const formFields = viewer.formFieldCollections; +``` + +## Read Text Field Values + +Find the text field by name and read its value property. For more information, see [`formFieldCollections`](./form-fields-api#formfieldcollections). + +```ts +const formFields = viewer.formFieldCollections; +const name = (formFields.find(field => field.type === 'Textbox' && field.name === 'name')).value; +``` + +## Read Checkbox / Radio Button Values + +Check whether a checkbox or radio button is selected by reading its `isChecked` value. For more information, see [`formFieldCollections`](./form-fields-api#formfieldcollections). + +```ts +const formFields = viewer.formFieldCollections; +const radioButtons = formFields.filter(field => a.type === 'RadioButton' && a.name === 'gender'); +const checkedField = (radioButtons.find(field => field.isChecked)).name; +``` + +## Read Dropdown values + +Read the dropdown’s selected option by accessing `value` property. For more information, see [`formFieldCollections`](./form-fields-api#formfieldcollections). + +```ts +const formFields = viewer.formFieldCollections; +const state = (formFields.find(field => field.type === 'DropdownList' && field.name === 'state')).value; +``` + +## Read Signature Field Data + +This reads the signature path data stored in a signature field so it can be later converted to an image. For more information, see [`formFieldCollections`](./form-fields-api#formfieldcollections). + +```ts +const formFields = viewer.formFieldCollections; +const signData = (formFields.find(field => field.type === 'SignatureField' && field.name === 'signature')).value; +``` + +## Extract All Form Field Values + +This iterates every field in the collection and logs each field's name and value, useful for exporting or validating all form data. For more information, see [`formFieldCollections`](./form-fields-api#formfieldcollections). + +```ts +const formFields = viewer.formFieldCollections; +formFields.forEach(field => { + if (field.type === 'RadioButton' || field.type === 'Checkbox') { + console.log(`${field.name}: ${field.isChecked}`); + } + else { + console.log(`${field.name}: ${field.value}`); + } +}); +``` + +## Extract Form Data After Document Loaded + +Place your form-reading logic inside `documentLoad` event handler, so values are read after the PDF is loaded in the viewer. For more information, see [`formFieldCollections`](./form-fields-api#formfieldcollections) and [`documentLoad`](../events#documentload). + +```ts +// If you need to access form data right after the PDF loads +viewer.documentLoaded = () => { + const formFields = viewer.formFieldCollections; + const email = formFields.find(field => field.name === 'email').value; + console.log("Email: ", email); +}; +``` + +## Use Cases + +- Validate and pre-fill form fields in your application before user submission. +- Submit filled form data from the viewer to a back end service for processing or storage. +- Synchronize form field values with external UI components to keep application state in sync. +- Export form data for reporting, archival, or integration with other systems. + +## Troubleshooting + +- Use the exact field names defined in the PDF when searching through the `formFieldCollections`. +- If a field might be missing in some documents, add null checks. + +## See also + +- [`formFieldCollections`](./form-fields-api#formfieldcollections) +- [`documentLoad`](../events#documentload) \ No newline at end of file diff --git a/Document-Processing/PDF/PDF-Viewer/react/forms/submit-form-data.md b/Document-Processing/PDF/PDF-Viewer/react/forms/submit-form-data.md new file mode 100644 index 0000000000..889e9a90a0 --- /dev/null +++ b/Document-Processing/PDF/PDF-Viewer/react/forms/submit-form-data.md @@ -0,0 +1,121 @@ +--- +layout: post +title: Submit PDF Form Data to a Server using React PDF Viewer | Syncfusion +description: Submit filled PDF form data from the EJ2 React PDF Viewer to a backend server, with a complete frontend example and a minimal Node receiver. +platform: document-processing +control: PDF Viewer +documentation: ug +domainurl: ##DomainURL## +--- + +# Submit PDF Form Data to a Server in React + +## Overview + +The React PDF Viewer allows submitting filled form data like text fields, checkboxes, radio buttons and dropdown values to a back end server for processing. This guide shows how to extract form data from the viewer and **post** it as `JSON` to a server endpoint. + +## Prerequisites + +- EJ2 React PDF Viewer installed and configured in your React app +- PDF contains interactive form fields +- The viewer must be loaded before reading values +- If posting cross-origin, ensure CORS is enabled on the server + +## Steps to send data + +1. Enable form designer in the viewer + + - Inject `FormFields` and `FormDesigner` services into the viewer so form APIs are available. + +2. Export form data from the viewer + + - Use `viewer.exportFormFieldsAsObject()` to obtain the filled values as JSON. + +3. POST the exported JSON to your back end + + - Use `fetch` to send the JSON. The server must accept `application/json` and handle CORS if cross-domain. + +4. Trigger submission from a UI action + + - Call the export + POST flow from a button click or form submit handler. + +## Example + +This full example shows a React component with the PDF viewer and a Submit button that sends form data to `/api/submit-form`. + +{% tabs %} +{% highlight ts tabtitle="App.tsx" %} +{% raw %} +import { + PdfViewerComponent, Toolbar, Magnification, Navigation, Annotation, LinkAnnotation, + ThumbnailView, BookmarkView, TextSelection, TextSearch, FormFields, FormDesigner, + PageOrganizer, Inject, Print +} from '@syncfusion/ej2-react-pdfviewer'; +import { RefObject, useRef } from 'react'; + +export default function SubmitFormExample() { + const viewerRef: RefObject = useRef(null); + + const sendToServer = async (formData: any) => { + // Adjust URL to your server endpoint + const res = await fetch('/api/submit-form', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(formData) + }); + if (!res.ok) { + throw new Error(`Server error ${res.status}`); + } + }; + + const handleSubmit = async () => { + try { + // exportFormFields returns a Promise resolving to form data object + const formData = await viewerRef.current.exportFormFieldsAsObject(); + await sendToServer(formData); + console.log('Form data submitted successfully.'); + } catch (err) { + console.error(err); + console.log('Submission failed: ' + (err as Error).message); + } + }; + + return ( +
    +
    + +
    + + + +
    + ); +} +{% endraw %} +{% endhighlight %} +{% endtabs %} + +## Troubleshooting + +- **No form values returned**: Ensure the PDF has interactive fields and the viewer has finished loading before calling `exportFormFieldsAsObject()`. +- **CORS errors**: Enable CORS on the server or serve both frontend and back end from the same origin during testing. +- **Server rejects payload**: Confirm the server expects `application/json` and validates shape of the object. +- **WASM or resource errors**: Ensure `resourceUrl` points to the correct Syncfusion PDF Viewer library files. + +## Use cases + +- Enable remote verification and approval workflows by sending submitted form data to a back end service for review and sign-off. +- Store submitted form responses in a database to persist user inputs for auditing, reporting, or later retrieval. +- Trigger workflow automation and downstream processing by sending form data to business systems or server less functions. +- Merge submitted values into a final flattened PDF on the server to produce a non-editable document that combines the form data with the original PDF. + +## Related topics + +- [`exportFormFieldsAsObject` API reference](./form-fields-api#exportformfieldsasobject) +- [Export form data as object](./import-export-form-fields/export-form-fields#export-as-object) \ No newline at end of file diff --git a/Document-Processing/PDF/PDF-Viewer/react/how-to/add-annotation-in-text-search.md b/Document-Processing/PDF/PDF-Viewer/react/how-to/add-annotation-in-text-search.md index a3113f93dd..68f6b7f685 100644 --- a/Document-Processing/PDF/PDF-Viewer/react/how-to/add-annotation-in-text-search.md +++ b/Document-Processing/PDF/PDF-Viewer/react/how-to/add-annotation-in-text-search.md @@ -1,132 +1,179 @@ --- layout: post -title: Add Rectangle Annotation via Text Search in Syncfusion React PDF Viewer -description: Discover how to add rectangle annotations via text search in the Syncfusion React PDF Viewer for a seamless mobile experience. +title: Add Annotations via Text Search in Syncfusion React PDF Viewer +description: Learn how to add annotations via text search events in the Syncfusion React PDF Viewer for a seamless mobile experience. control: PDF Viewer platform: document-processing documentation: ug --- -# Add Rectangle Annotations via Text Search in PDF Viewer +# Add Annotations via Text Search in PDF Viewer -A concise guide that demonstrates how to add rectangle annotations at highlighted text search results in the React PDF Viewer. The guide explains where to wire the callback, required services, and quick troubleshooting steps. +A concise guide that demonstrates how to add rectangle and highlight annotations at highlighted text search results in the React PDF Viewer. The guide explains where to wire the callback, required services, and quick troubleshooting steps. -## Steps to add rectangle annotations on search result highlight +## Prerequisites + +A React PDF Viewer setup with [`Annotation`](https://ej2.syncfusion.com/react/documentation/api/pdfviewer/annotation) module injected. + +## Steps to add rectangle or highlight annotations on search result highlight **Step 1:** Follow the steps provided in the [Syncfusion® Getting Started Guide](https://help.syncfusion.com/document-processing/pdf/pdf-viewer/react/getting-started) to set up a basic PDF Viewer sample. -**Step 2:** Set up the PDF Viewer component to add rectangle annotations based on the bounds of highlighted search text in the PDF Viewer. +**Step 2a:** Set up the PDF Viewer component to add rectangle annotations based on the bounds of highlighted search text in the PDF Viewer. {% tabs %} {% highlight js tabtitle="Standalone" %} {% raw %} - -import React from 'react'; -import ReactDOM from 'react-dom/client'; -import './index.css'; +import { RefObject, useRef } from 'react'; import { - PdfViewerComponent, - Toolbar, - Magnification, - Navigation, - Annotation, - TextSelection, - TextSearch, - FormFields, - FormDesigner, - PageOrganizer, - Inject + PdfViewerComponent, Toolbar, Magnification, Navigation, Annotation, TextSelection, + TextSearch, FormFields, FormDesigner, PageOrganizer, Print, Inject, RectangleSettings, + TextSearchHighlightEventArgs, RectangleBoundsModel } from '@syncfusion/ej2-react-pdfviewer'; -class App extends React.Component { - constructor(props) { - super(props); - // Create a ref for the PdfViewerComponent to access its methods and properties - this.viewerRef = React.createRef(); - } - - componentDidMount() { - // Obtain the current instance of the PdfViewerComponent - const viewer = this.viewerRef.current; - - if (viewer) { - // Attach an event handler for text search highlight - viewer.textSearchHighlight = this.handleTextSearchHighlight; - } - } - - // Method to handle the text search highlight event - handleTextSearchHighlight = (args) => { - console.log(args); // Logs Highlighted text search details - - const pageNumber = args.pageNumber; - const bounds = args.bounds; - - // Add a rectangle annotation on the highlighted text - this.viewerRef.current.annotationModule.addAnnotation('Rectangle', { - pageNumber: pageNumber, - offset: { x: bounds.left, y: bounds.top }, - width: bounds.width, - height: bounds.height, - }); - }; - - // Method to initiate a text search for the term 'PDF' - handleSearch = () => { - this.viewerRef.current.textSearchModule.searchText('PDF', false); - }; - - // Method to go to the next instance of the search term - handleSearchNext = () => { - this.viewerRef.current.textSearchModule.searchNext(); - }; - - // Method to cancel the current text search operation - handleCancelSearch = () => { - this.viewerRef.current.textSearchModule.cancelTextSearch(); - }; - - render() { +export default function App() { + const viewerRef: RefObject = useRef(null); + + // Method to handle the text search highlight event + const handleTextSearchHighlight = (args: TextSearchHighlightEventArgs) => { + console.log(args); // Logs Highlighted text search details + + const pageNumber: number = args.pageNumber; + const bounds: RectangleBoundsModel = args.bounds; + + // Add a rectangle annotation on the highlighted text + viewerRef.current.annotationModule.addAnnotation('Rectangle', { + pageNumber: pageNumber, + offset: { x: bounds.left, y: bounds.top }, + width: bounds.width, + height: bounds.height, + } as RectangleSettings); + }; + + // Method to initiate a text search for the term 'PDF' + const handleSearch = () => { + viewerRef.current.textSearchModule.searchText('PDF', false); + }; + + // Method to go to the next instance of the search term + const handleSearchNext = () => { + viewerRef.current.textSearchModule.searchNext(); + }; + + // Method to cancel the current text search operation + const handleCancelSearch = () => { + viewerRef.current.textSearchModule.cancelTextSearch(); + }; + return ( -
    -
    - - - -
    -
    - - - -
    -
    - ); -} +
    +
    + + + +
    +
    + + + +
    +
    + ); } +{% endraw %} +{% endhighlight %} +{% endtabs %} + +**Expected result:** Rectangle annotations are added at text search result locations, improving visibility for users navigating search matches. + +**Step 2b:** Set up the PDF Viewer component to add highlight annotations based on the bounds of highlighted search text in the PDF Viewer. + +{% tabs %} +{% highlight js tabtitle="Standalone" %} +{% raw %} +import { RefObject, useRef } from 'react'; +import { + PdfViewerComponent, Toolbar, Magnification, Navigation, Annotation, TextSelection, + TextSearch, FormFields, FormDesigner, PageOrganizer, Print, Inject, TextSearchHighlightEventArgs, + HighlightSettings, IAnnotationPoint +} from '@syncfusion/ej2-react-pdfviewer'; -const root = ReactDOM.createRoot(document.getElementById('sample')); -root.render(); +export default function App() { + const viewerRef: RefObject = useRef(null); + + // Method to handle the text search highlight event + const handleTextSearchHighlight = (args: TextSearchHighlightEventArgs) => { + console.log(args); // Logs Highlighted text search details + + const pageNumber: number = args.pageNumber; + const bounds: IAnnotationPoint[] = [{ + x: args.bounds.x ?? args.bounds.left, + y: args.bounds.y ?? args.bounds.top, + height: args.bounds.height, + width: args.bounds.width + }]; + + // Add a highlight annotation on the highlighted text + viewerRef.current.annotation.addAnnotation('Highlight', { + pageNumber: pageNumber, + bounds: bounds + } as HighlightSettings); + }; + + // Method to initiate a text search for the term 'PDF' + const handleSearch = () => { + viewerRef.current.textSearchModule.searchText('PDF', false); + }; + + // Method to go to the next instance of the search term + const handleSearchNext = () => { + viewerRef.current.textSearchModule.searchNext(); + }; + + // Method to cancel the current text search operation + const handleCancelSearch = () => { + viewerRef.current.textSearchModule.cancelTextSearch(); + }; + return ( +
    +
    + + + +
    +
    + + + +
    +
    + ); +} {% endraw %} {% endhighlight %} {% endtabs %} -Following this guide enables the PDF Viewer to add rectangle annotations at text search result locations, improving visibility for users navigating search matches. +**Expected result:** Highlight annotation is added at text search result locations, improving visibility for users navigating search matches. -[View sample on GitHub](https://github.com/SyncfusionExamples/react-pdf-viewer-examples/tree/master/How%20to) +[View sample the complete working sample on GitHub](https://github.com/SyncfusionExamples/react-pdf-viewer-examples/tree/master/How%20to)