Skip to content

Commit 4fc0380

Browse files
1013392: Added form field files for react docs revamp
1 parent 877c9ad commit 4fc0380

4 files changed

Lines changed: 351 additions & 0 deletions

File tree

Document-Processing-toc.html

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1051,6 +1051,9 @@
10511051
<li><a href="/document-processing/pdf/pdf-viewer/react/how-to/custom-fonts">Custom fonts</a></li>
10521052
<li><a href="/document-processing/pdf/pdf-viewer/react/forms/form-field-events">Form Field events</a></li>
10531053
<li><a href="/document-processing/pdf/pdf-viewer/react/forms/form-fields-api">APIs</a></li>
1054+
<li><a href="/document-processing/pdf/pdf-viewer/react/forms/flatten-form-fields">Flatten form fields</a></li>
1055+
<li><a href="/document-processing/pdf/pdf-viewer/react/forms/read-form-field-values">Read form fields</a></li>
1056+
<li><a href="/document-processing/pdf/pdf-viewer/react/forms/submit-form-data">Submit form data</a></li>
10541057
</ul>
10551058
</li>
10561059
<li><a href="/document-processing/pdf/pdf-viewer/react/organize-pages/overview">Organize Pages</a>
Lines changed: 121 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,121 @@
1+
---
2+
layout: post
3+
title: Flatten PDF form fields in React PDF Viewer | Syncfusion
4+
description: Learn hoow to flatten interactive PDF form fields before download or save-as in EJ2 React PDF Viewer.
5+
platform: document-processing
6+
control: PDF Viewer
7+
documentation: ug
8+
domainurl: ##DomainURL##
9+
---
10+
11+
# Flatten PDF form fields in React
12+
13+
## Overview
14+
15+
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.
16+
17+
## Prerequisites
18+
19+
- EJ2 React PDF Viewer installed and configured
20+
- Basic viewer setup completed with toolbar and page organizer services injected. For more information, see [getting started guide](../getting-started)
21+
22+
## Flatten forms before downloading PDF
23+
24+
1. Add a ref to the `PdfViewerComponent` so you can access viewer APIs from event handlers.
25+
2. Intercept the download flow using `downloadStart` and cancel the default flow.
26+
3. Retrieve the viewer's blob via `saveAsBlob()` and convert the blob to base64.
27+
4. Use `PdfDocument` from Syncfusion PDF Library to open the document, set `field.flatten = true` for each form field, then save.
28+
5. For the flattening the form fields when downloading through *Save As* option in Page Organizer, repeat steps 2–4 by using `pageOrganizerSaveAs` event.
29+
30+
## Complete example
31+
32+
{% tabs %}
33+
{% highlight ts tabtitle="App.tsx" %}
34+
{% raw %}
35+
import {
36+
PdfViewerComponent, Toolbar, Magnification, Navigation, Annotation, LinkAnnotation,
37+
ThumbnailView, BookmarkView, TextSelection, TextSearch, FormFields, FormDesigner,
38+
PageOrganizer, Inject, Print, PageOrganizerSaveAsEventArgs, DownloadStartEventArgs
39+
} from '@syncfusion/ej2-react-pdfviewer';
40+
import { PdfDocument, PdfField } from '@syncfusion/ej2-pdf';
41+
import { RefObject, useRef } from 'react';
42+
43+
export default function App() {
44+
const viewerRef: RefObject<PdfViewerComponent> = useRef(null);
45+
46+
const blobToBase64 = async (blob: Blob): Promise<string> => {
47+
return new Promise((resolve, reject) => {
48+
const reader = new FileReader();
49+
reader.onerror = () => reject(reader.error);
50+
reader.onload = () => {
51+
const dataUrl: string = reader.result as string;
52+
const data: string = dataUrl.split(',')[1];
53+
resolve(data);
54+
};
55+
reader.readAsDataURL(blob);
56+
});
57+
}
58+
59+
const flattenFormFields = (data: string) => {
60+
let document: PdfDocument = new PdfDocument(data);
61+
for (let index = 0; index < document.form.count; index++) {
62+
let field: PdfField = document.form.fieldAt(index);
63+
field.flatten = true;
64+
}
65+
// If both annotations and form fields needs to be flattened, use
66+
// document.flatten = true
67+
document.save(`${viewerRef.current.fileName}.pdf`);
68+
document.destroy();
69+
}
70+
71+
const handleFlattening = async () => {
72+
const blob: Blob = await viewerRef.current.saveAsBlob();
73+
const data: string = await blobToBase64(blob);
74+
flattenFormFields(data);
75+
}
76+
77+
const onDownloadStart = async (args: DownloadStartEventArgs) => {
78+
args.cancel = true;
79+
handleFlattening();
80+
};
81+
82+
const onPageOrganizerSaveAs = async (args: PageOrganizerSaveAsEventArgs) => {
83+
args.cancel = true;
84+
handleFlattening()
85+
};
86+
87+
return (
88+
<div style={{ height: '640px' }}>
89+
<PdfViewerComponent
90+
id="pdf-viewer"
91+
ref={viewerRef}
92+
documentPath="https://cdn.syncfusion.com/content/pdf/form-filling-document.pdf"
93+
resourceUrl="https://cdn.syncfusion.com/ej2/32.2.5/dist/ej2-pdfviewer-lib"
94+
pageOrganizerSaveAs={onPageOrganizerSaveAs}
95+
downloadStart={onDownloadStart}
96+
>
97+
<Inject services={[Toolbar, Magnification, Navigation, Annotation, LinkAnnotation, ThumbnailView,
98+
BookmarkView, TextSelection, TextSearch, FormFields, FormDesigner, PageOrganizer, Print]} />
99+
</PdfViewerComponent>
100+
</div>
101+
);
102+
}
103+
{% endraw %}
104+
{% endhighlight %}
105+
{% endtabs %}
106+
107+
## Expected result
108+
109+
- The downloaded or "Save As" PDF will contain the visible appearance of filled form fields as static, non-editable content.
110+
- Form fields will no longer be interactive or editable in common PDF readers.
111+
112+
## Troubleshooting
113+
114+
- If viewerRef is null, ensure `ref={viewerRef}` is present and the component has mounted before invoking `saveAsBlob()`.
115+
- Missing `resourceUrl`: If viewer resources are not reachable, set `resourceUrl` to the correct CDN or local path for the ej2-pdfviewer-lib.
116+
117+
## Related topics
118+
119+
- [`downloadStart` event reference](../events#downloadstart)
120+
- [`pageOrganizerSaveAs` event reference](../events#pageorganizersaveas)
121+
- [Form Designer in React PDF Viewer](./form-designer)
Lines changed: 106 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,106 @@
1+
---
2+
layout: post
3+
title: Read and Extract PDF Form Field Values in React PDF Viewer | Syncfusion
4+
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.
5+
platform: document-processing
6+
control: PDF Viewer
7+
documentation: ug
8+
domainurl: ##DomainURL##
9+
---
10+
11+
# Read and Extract PDF Form Field Values in React PDF Viewer
12+
13+
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.
14+
15+
This guide shows common patterns with concise code snippets you can copy into your React components.
16+
17+
## Access the Form Field Collection
18+
19+
Get all available form field ata by reading viewer's `formFieldCollections`. For more information, see [`formFieldCollections`](./form-fields-api#formfieldcollections).
20+
21+
```ts
22+
const formFields = viewer.formFieldCollections;
23+
```
24+
25+
## Read Text Field Values
26+
27+
Find the text field by name and read its value property. For more information, see [`formFieldCollections`](./form-fields-api#formfieldcollections).
28+
29+
```ts
30+
const formFields = viewer.formFieldCollections;
31+
const name = (formFields.find(field => field.type === 'Textbox' && field.name === 'name')).value;
32+
```
33+
34+
## Read Checkbox / Radio Button Values
35+
36+
Check whether a checkbox or radio button is selected by reading its `isChecked` value. For more information, see [`formFieldCollections`](./form-fields-api#formfieldcollections).
37+
38+
```ts
39+
const formFields = viewer.formFieldCollections;
40+
const radioButtons = formFields.filter(field => a.type === 'RadioButton' && a.name === 'gender');
41+
const checkedField = (radioButtons.find(field => field.isChecked)).name;
42+
```
43+
44+
## Read Dropdown values
45+
46+
Read the dropdown’s selected option by accessing `value` property. For more information, see [`formFieldCollections`](./form-fields-api#formfieldcollections).
47+
48+
```ts
49+
const formFields = viewer.formFieldCollections;
50+
const state = (formFields.find(field => field.type === 'DropdownList' && field.name === 'state')).value;
51+
```
52+
53+
## Read Signature Field Data
54+
55+
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).
56+
57+
```ts
58+
const formFields = viewer.formFieldCollections;
59+
const signData = (formFields.find(field => field.type === 'SignatureField' && field.name === 'signature')).value;
60+
```
61+
62+
## Extract All Form Field Values
63+
64+
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).
65+
66+
```ts
67+
const formFields = viewer.formFieldCollections;
68+
formFields.forEach(field => {
69+
if (field.type === 'RadioButton' || field.type === 'Checkbox') {
70+
console.log(`${field.name}: ${field.isChecked}`);
71+
}
72+
else {
73+
console.log(`${field.name}: ${field.value}`);
74+
}
75+
});
76+
```
77+
78+
## Extract Form Data After Document Loaded
79+
80+
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).
81+
82+
```ts
83+
// If you need to access form data right after the PDF loads
84+
viewer.documentLoaded = () => {
85+
const formFields = viewer.formFieldCollections;
86+
const email = formFields.find(field => field.name === 'email').value;
87+
console.log("Email: ", email);
88+
};
89+
```
90+
91+
## Use Cases
92+
93+
- Validate and pre-fill form fields in your application before user submission.
94+
- Submit filled form data from the viewer to a backend service for processing or storage.
95+
- Synchronize form field values with external UI components to keep application state in sync.
96+
- Export form data for reporting, archival, or integration with other systems.
97+
98+
## Troubleshooting
99+
100+
- Use the exact field names defined in the PDF when searching through the `formFieldCollections`.
101+
- If a field might be missing in some documents, add null checks.
102+
103+
## See also
104+
105+
- [`formFieldCollections`](./form-fields-api#formfieldcollections)
106+
- [`documentLoad`](../events#documentload)
Lines changed: 121 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,121 @@
1+
---
2+
layout: post
3+
title: Submit PDF Form Data to a Server using React PDF Viewer | Syncfusion
4+
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.
5+
platform: document-processing
6+
control: PDF Viewer
7+
documentation: ug
8+
domainurl: ##DomainURL##
9+
---
10+
11+
# Submit PDF Form Data to a Server in React
12+
13+
## Overview
14+
15+
The React PDF Viewer allows submitting filled form data like text fields, checkboxes, radio buttons and dropdown values to a backend server for processing. This guide shows how to extract form data from the viewer and **post** it as `JSON` to a server endpoint.
16+
17+
## Prerequisites
18+
19+
- EJ2 React PDF Viewer installed and configured in your React app
20+
- PDF contains interactive form fields
21+
- The viewer must be loaded before reading values
22+
- If posting cross-origin, ensure CORS is enabled on the server
23+
24+
## Steps to send data
25+
26+
1. Enable form designer in the viewer
27+
28+
- Inject `FormFields` and `FormDesigner` services into the viewer so form APIs are available.
29+
30+
2. Export form data from the viewer
31+
32+
- Use `viewer.exportFormFieldsAsObject()` to obtain the filled values as JSON.
33+
34+
3. POST the exported JSON to your backend
35+
36+
- Use `fetch` or `axios` to send the JSON. The server must accept `application/json` and handle CORS if cross-domain.
37+
38+
4. Trigger submission from a UI action
39+
40+
- Call the export + POST flow from a button click or form submit handler.
41+
42+
## Example
43+
44+
This full example shows a React component with the PDF viewer and a Submit button that sends form data to `/api/submit-form`.
45+
46+
{% tabs %}
47+
{% highlight ts tabtitle="App.tsx" %}
48+
{% raw %}
49+
import {
50+
PdfViewerComponent, Toolbar, Magnification, Navigation, Annotation, LinkAnnotation,
51+
ThumbnailView, BookmarkView, TextSelection, TextSearch, FormFields, FormDesigner,
52+
PageOrganizer, Inject, Print
53+
} from '@syncfusion/ej2-react-pdfviewer';
54+
import { RefObject, useRef } from 'react';
55+
56+
export default function SubmitFormExample() {
57+
const viewerRef: RefObject<PdfViewerComponent> = useRef<PdfViewerComponent>(null);
58+
59+
const sendToServer = async (formData: any) => {
60+
// Adjust URL to your server endpoint
61+
const res = await fetch('/api/submit-form', {
62+
method: 'POST',
63+
headers: { 'Content-Type': 'application/json' },
64+
body: JSON.stringify(formData)
65+
});
66+
if (!res.ok) {
67+
throw new Error(`Server error ${res.status}`);
68+
}
69+
};
70+
71+
const handleSubmit = async () => {
72+
try {
73+
// exportFormFields returns a Promise resolving to form data object
74+
const formData = await viewerRef.current.exportFormFieldsAsObject();
75+
await sendToServer(formData);
76+
console.log('Form data submitted successfully.');
77+
} catch (err) {
78+
console.error(err);
79+
console.log('Submission failed: ' + (err as Error).message);
80+
}
81+
};
82+
83+
return (
84+
<div style={{ height: '640px' }}>
85+
<div style={{ marginBottom: '8px' }}>
86+
<button onClick={handleSubmit}>Submit form data</button>
87+
</div>
88+
<PdfViewerComponent
89+
id="pdfViewer"
90+
ref={viewerRef}
91+
documentPath="https://cdn.syncfusion.com/content/pdf/form-filling-document.pdf"
92+
resourceUrl="https://cdn.syncfusion.com/ej2/32.2.5/dist/ej2-pdfviewer-lib"
93+
style={{ height: '100%' }}>
94+
<Inject services={[Toolbar, Magnification, Navigation, Annotation, LinkAnnotation, ThumbnailView,
95+
BookmarkView, TextSelection, TextSearch, FormFields, FormDesigner, PageOrganizer, Print]} />
96+
</PdfViewerComponent>
97+
</div>
98+
);
99+
}
100+
{% endraw %}
101+
{% endhighlight %}
102+
{% endtabs %}
103+
104+
## Troubleshooting
105+
106+
- **No form values returned**: Ensure the PDF has interactive fields and the viewer has finished loading before calling `exportFormFieldsAsObject()`.
107+
- **CORS errors**: Enable CORS on the server or serve both frontend and backend from the same origin during testing.
108+
- **Server rejects payload**: Confirm the server expects `application/json` and validates shape of the object.
109+
- **WASM or resource errors**: Ensure `resourceUrl` points to the correct Syncfusion PDF Viewer library files.
110+
111+
## Use cases
112+
113+
- Enable remote verification and approval workflows by sending submitted form data to a backend service for review and sign-off.
114+
- Store submitted form responses in a database to persist user inputs for auditing, reporting, or later retrieval.
115+
- Trigger workflow automation and downstream processing by sending form data to business systems or serverless functions.
116+
- 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.
117+
118+
## Related topics
119+
120+
- [`exportFormFieldsAsObject` API reference](./form-fields-api#exportformfieldsasobject)
121+
- [Export form data as object](./import-export-form-fields/export-form-fields#export-as-object)

0 commit comments

Comments
 (0)