Document Reader SDK Web Components
- Overview
- Before you start
- Compatibility
- Predefined UI Components
- npm Service Integration
- CDN Service Integration
- Service Parameters
- Events
- Settings and Attributes
- Backend reprocessing
- Appearance Customization
- Document Reader Processor
- npm Processor Integration
- CDN Processor Integration
- Processor Methods
- Processor Parameters
- Package Resources
- Potential Problems
- Examples
- Additional Resources
- FAQ
- How do I collect logs?
Overview
The Document Reader Web Components let you add document verification to your website, including the features:
- Capture a document from the device's camera
- Process an uploaded image
- Crop the image by document boundaries
- Detect the presence of a machine-readable zone (MRZ)
- Recognize and return the values of MRZ text fields
The Document Reader Web Components package contains:
- Predefined UI Components
Document Reader UI Web Components with predefined view and behavior are designed for the fast integration of document recognition functionality into your project. You can still customize most of the appearance and processing parameters before the launch if needed. Examples of the UI Web Components aredocument-reader
for documents recognition,camera-snapshot
for capturing images from a camera or uploading from a gallery. - Processor
Document Reader Processor manages the document image recognition and other related operations, leaving implementation of UI to you.
Current document acts as a quick start guide for operating Document Reader Web Components and as a reference to their main processing parameters.
Before You Start
Important notes:
- Never keep the license in production environment. On production environments, the domain name licensing method must be used. Using the license in the source code of your project is applicable only in development and for testing.
- Document Reader Web Components and their methods strictly require the secure contexts, so using HTTPS protocol is a must.
- The considered components are registered on the web page itself, so make sure to import the library to your website before adding any of the components to the web page code.
- Only the modern browser versions are supported, see compatibility. Polyfills are not included in the package by default.
Compatibility
Devices | |||
---|---|---|---|
Mobile (iOS) | 99 | 99 | 11 |
Mobile (Android) | 66 | 63 | - |
Desktop | 61 | 63 | 11 |
To support the older browser versions in your project, install the required polyfill packages manually. Follow the link to npm package @webcomponents/webcomponentsjs for installation details.
Predefined UI Components
npm Service Integration
Step 1. Install the package @regulaforensics/vp-frontend-document-components
:
npm i @regulaforensics/vp-frontend-document-components
Step 2. Import the function defineComponents
and the class DocumentReaderService
into your .js
file.
Using module bundler:
import { defineComponents, DocumentReaderService } from '@regulaforensics/vp-frontend-document-components';
import { defineComponents, DocumentReaderService } from './node_modules/@regulaforensics/vp-frontend-document-components/dist/main.js';
Step 3. Define the components, depending on the functionality that you need.
If you need only the camera-snapshot
component, call the defineComponents()
method without arguments:
defineComponents();
If you need the entire scope of functionality:
1. Add DocumentReaderService
to the global variable RegulaDocumentSDK
and set processing scenario:
window.RegulaDocumentSDK = new DocumentReaderService();
window.RegulaDocumentSDK.recognizerProcessParam = {
processParam: {
scenario: 'MrzAndLocate',
},
};
window.RegulaDocumentSDK.imageProcessParam = {
processParam: {
scenario: 'MrzAndLocate',
},
};
On production environment (the domain name licensing is used):
defineComponents().then(() => window.RegulaDocumentSDK.initialize());
On test environment (with generated Base64 license string):
defineComponents().then(() => window.RegulaDocumentSDK.initialize({ license: 'BASE64_LICENSE_KEY' }));
For more information about licensing, see the Document Reader SDK Licensing page and the How to Convert a License File to BASE64 FAQ article.
Step 4. Add the desired component tag to the .html
file.
For example:
document-reader
is used for the document recognition with defined parameters:
<document-reader></document-reader>
camera-snapshot
is used to capture images from the device's camera and to import from the gallery:
<camera-snapshot></camera-snapshot>
CDN Service Integration
Step 1. Connect the script to your .html
file.
Use the CDN link in a format as follows: unpkg.com/:package@:version/:file
For example:
<script src="https://unpkg.com/@regulaforensics/vp-frontend-document-components@latest/dist/main.iife.js"></script>
Note: You can find all available script versions in the corresponding section of npm, using the same link from the previous example.
Step 2. Define the components, depending on the functionality that you need.
If you need only the camera-snapshot
component:
defineComponents();
If you need the entire scope of functionality:
1. Access DocumentReaderService
and defineComponents
via the global variable window.Regula
:
const { defineComponents, DocumentReaderService } = window.Regula;
DocumentReaderService
to the global variable RegulaDocumentSDK
and set processing scenario:
window.RegulaDocumentSDK = new DocumentReaderService();
window.RegulaDocumentSDK.recognizerProcessParam = {
processParam: {
scenario: 'MrzAndLocate',
},
};
window.RegulaDocumentSDK.imageProcessParam = {
processParam: {
scenario: 'MrzAndLocate',
},
};
On production environment (the domain name licensing is used):
defineComponents().then(() => window.RegulaDocumentSDK.initialize());
On test environment (with generated Base64 license string):
defineComponents().then(() => window.RegulaDocumentSDK.initialize({ license: 'BASE64_LICENSE_KEY' }));
For more information about licensing, see the Document Reader SDK Licensing page and the How to Convert a License File to BASE64 FAQ article.
Service Parameters
After adding DocumentReaderService
to the global variable, you can change the default document recognition and image processing settings as follows:
Image recognition (video capture) default settings. The functionality is available via the camera button.
window.RegulaDocumentSDK.recognizerProcessParam = {
processParam: {
returnUncroppedImage: true,
multipageProcessing: false,
returnPackageForReprocess: false,
timeout: 20000,
resultTypeOutput: [],
imageQa: {
expectedPass: ['dpiThreshold', 'glaresCheck', 'focusCheck'],
dpiThreshold: 130,
glaresCheck: true,
glaresCheckParams: {
imgMarginPart: 0.05,
maxGlaringPart: 0.01,
},
},
},
};
Image processing default settings. The functionality is available via the gallery button.
window.RegulaDocumentSDK.imageProcessParam = {
processParam: {
returnUncroppedImage: true,
returnPackageForReprocess: false,
},
};
Session ID for image processing:
window.RegulaDocumentSDK.imageProcessParam = {
tag: 'your session id',
};
Parameters Description
Setting | Info | Data type | Default value | Values |
---|---|---|---|---|
returnUncroppedImage | When enabled, returns input images in output. | boolean | true |
true , false |
scenario | Recognition scenario. | string | 'MrzAndLocate' | 'MrzAndLocate', 'MrzOrLocate', 'Mrz', 'Locate' |
multipageProcessing | Whether to enable multi-page document processing mode. | boolean | true |
true , false |
timeout | Recognition timeout in milliseconds. After this time process will be finished. | number | 2000 | numbers > 0 |
resultTypeOutput | Types of results to return in response. [] - all available types. | number[] | [] | 1 - DocumentImageResult, 3 - TextDataResult, 5 - DocBarCodeInfo, 6 - GraphicsResult, 8 - DocumentTypesCandidatesResult, 9 - ChosenDocumentTypeResult, 20 - AuthenticityResult, 15 - LexicalAnalysisResult, 17 - TextDataResult, 18 - TextDataResult, 19 - GraphicsResult, 30 - ImageQualityResult, 33 - StatusResult, 36 - TextResult, 37 - ImagesResult, 85 - DocumentPositionResult, 102 - TextDataResult, 103 - GraphicsResult, 50 - LicenseResult, 49 - EncryptedRCLResult |
returnPackageForReprocess | When enabled, returns the package for reprocessing on the backend. | boolean | false |
true , false |
imageQa | When enabled, image quality checks status affects document optical and overall status. | |||
respectImageQuality | When enabled, image quality checks status affects document optical and overall status. | boolean | false |
true , false |
expectedPass | Activated image quality checks. | string[] | ['dpiThreshold', 'glaresCheck', 'focusCheck'] | 'dpiThreshold', 'glaresCheck', 'focusCheck' |
documentAreaMin | Specifies minimal area of the image that document should cover to be treated as candidate when locating. Value should be in range from 0 to 1, where 1 is when document should fully cover the image. | number | 0 | from 0 to 1 |
dpiThreshold | This parameter sets threshold for Image QA check of the presented document physical dpi. If actual document dpi is below this threshold, check will fail. | number | 150 | numbers > 0 |
angleThreshold | This parameter set threshold for Image QA check of the actual document perspective angle (in degrees), above which the check fails. | number | numbers > 0 | |
focusCheck | This option enables the focus check for the image quality validation. | boolean | true |
true , false |
colornessCheck | This option enables the colorness check while performing image quality validation. | boolean | false |
true , false |
brightnessThreshold | This option sets the threshold for an actual document brightness, below which the check fails. | number | numbers > 0 | |
documentPositionIndent | This parameter sets the minimum indent (as a percentage of document width) from the corners of the document to the borders of the image. If the corners of the document are closer than the specified value, the status will contain an error in the documentPosition field. |
number | 0 | from 0 to 100 |
glaresCheck | This option enables glares check while performing image quality validation. | boolean | true |
true , false |
glaresCheckParams | Advanced settings for glare check. | |||
glaresCheckParams.imgMarginPart | Relative indent from the side of the document, ignored during the glares check. The check is still performed on the document area closer to the center. | number | 0 | from 0 to 1 |
glaresCheckParams.maxGlaringPart | Relative maximum size of glare-like objects that aren't considered as glares. Only the objects having area, greater than the specified value, are taken into account. | number | from 0 to 1 |
|
imageOutputMaxHeight | This parameter allows setting maximum height in pixels of output images and thus reducing image size to desired. Does not change the aspect ratio. Changes disabled if equals to 0. | number | 0 | numbers > 0 |
imageOutputMaxWidth | This parameter allows setting maximum width in pixels of output images and thus reducing image size to desired. Does not change the aspect ratio. Changes disabled if equals to 0. | number | 0 | numbers > 0 |
fieldTypesFilter | List of text field types to extract. If empty, all text fields from template will be extracted. Narrowing the list can shorten processing time. | number[] | [] | |
dateFormat | This option allows you to set dates format so that solution will return dates in this format. For example, if you supply 'MM/dd/yyyy', and document have printed date '09 JUL 2020' for the date os issue, you will get '07/09/2020' as a result. By default it is set to system locale default (where the service is running). | string | 'MM/dd/yyyy' | |
measureSystem | This option allows you to set the system of measurement used for converting original values in document to output result values. Metric by default. | number | 0 | 0 - Metric, 1 - Imperial |
imageDpiOutMax | This parameter controls maximum resolution in dpi of output images. Resolution will remain original in case 0 is supplied. By default is set to return images in response with resolution not greater than 300 dpi for all scenarios except FullAuth. In FullAuth scenario this limit is 1000 dpi by default. | number | numbers > 0 | |
alreadyCropped | This option can be enabled if you know for sure that the image you provide contains already cropped document by its edges. This was designed to process on the server side images captured and cropped on mobile. | boolean | false |
true , false |
customParams | This option allows passing custom processing parameters that can be implemented in future without changing API. | Object | {} | |
fastDocDetect (deprecated) | When enabled, shorten the list of candidates to process during document detection in a single image process mode. Reduces processing time for specific backgrounds. | boolean | true |
true , false |
updateOCRValidityByGlare | When enabled, fail OCR field validity, if there is a glare over the text field on the image. | boolean | false |
true , false |
returnCroppedBarcode | When enabled, returns cropped barcode images for unknown documents. | boolean | false |
true , false |
forceDocFormat | Force use of specified document format when locating and recognizing document to reduce the number of candidates. | number | 0 - ID1 document format, 1 - ID2 document format, 2 - ID3 document format, 3 - Undefined document format, 4 - A4 document format, 5 - ID3 double document format, 10 - ID1 format document rotated 90°, 11 - ID1 format document rotated 180°, 12 - ID1 format document rotated 270°, 13 - ID2 format document rotated 90°, 14 - ID3 format document rotated 180°, 1000 - Arbitrary format, 1002 - Flexible format. Standard formats can be resized during cropping, depending on various factors: light, background... |
|
noGraphics | When enabled, no graphic fields will be cropped from document image. | boolean | false |
true , false |
depersonalizeLog | When enabled, all personal data will be forcibly removed from the logs. | boolean | false |
true , false |
multiDocOnImage | This option allows locating and cropping multiple documents from one image if enabled. | boolean | false |
true , false |
shiftExpiryDate | This option allows shifting the date of expiry into the future or past for number of months specified. This is useful, for example, in some cases when document might be still valid for some period after original expiration date to prevent negative validity status for such documents. Or by shifting the date to the past will set negative validity for the documents that is about to expire in a specified number of months. | number | 0 | numbers > 0 |
minimalHolderAge | This options allows specifying the minimal age in years of the document holder for the document to be considered valid. | number | 0 | numbers > 0 |
mrzFormatsFilter | This option allows limiting MRZ formats to be recognized by specifying them in array. | string[] | [] | '1x30' - IDL, '3x30' - ID1, '2x36' - ID2, '2x44' - ID3, '1x6' - CAN, '2x30' - ID1 2x30 |
forceReadMrzBeforeLocate | When enabled, make sure that in series processing MRZ is located fully inside the result document image, if present on the document. Enabling this option may add extra processing time, by disabling optimizations, but allows more stability in output image quality. | boolean | false |
true , false |
parseBarcodes | This option can be disabled to stop parsing after barcode is read. | boolean | true |
true , false |
splitNames | When enabled, the Surname and GivenNames fields will be divided into ft_First_Name, ft_Second_Name, ft_Third_Name, ft_Fourth_Name, ft_Last_Name fields. | boolean | false |
true , false |
backendProcessing | When enabled, it prepares the processing result to be sent to the backend for re-processing. Use service.finalizePackage(); after receiving the processing results to send them to the backend. |
Object | {} | { serviceURL: 'URL', httpHeaders: { key1: 'header1', key2: 'header2', ... } } |
generateNumericCodes | This parameter is used to generate numeric representation for issuing state and nationality codes. | boolean | false |
true , false |
Attention! If the multipage-processing
or internal-scenario
attributes are set, the corresponding multipageProcessing
and scenario
parameters' values are ignored.
Events
The main idea of a subscription to different events is to detect the specific state changes of the concrete component. For the convenience, the event has the same name as the component that it belongs to.
For example, the next code snippet adds the event listeners to document-reader
and camera-snapshot
components:
const documentReaderComponent = document.querySelector('document-reader');
const cameraSnapshotComponent = document.querySelector('camera-snapshot');
documentReaderComponent.addEventListener('document-reader', (event) => console.log(event.detail));
cameraSnapshotComponent.addEventListener('camera-snapshot', (event) => console.log(event.detail));
To provide the detailed information about how the event was generated and executed, the special object event.detail
is generated.
See event.detail
object structure in the following code snippet:
{
action: 'PRESS_CAMERA_BUTTON',
data: null,
}
The fields of the event.detail
object:
* action
contains the type of action that generated the component's event. For more information, see all available action types.
* data
keeps the object with status of executed action and the payload. For more information, see the action data section.
Action Types
Type of action | Description of the action | Components and events, where present |
---|---|---|
ELEMENT_VISIBLE |
Component is appended in the DOM. | document-reader , camera-snapshot |
PRESS_CAMERA_BUTTON |
The "From camera" button is pressed. | document-reader , camera-snapshot |
PRESS_FILE_BUTTON |
The "From gallery" button is pressed. | document-reader , camera-snapshot |
PRESS_RETRY_BUTTON |
The "Retry" button is pressed. | document-reader , camera-snapshot |
PRESS_SKIP_BUTTON |
The "Skip" button is pressed. | document-reader |
PRESS_CAPTURE_BUTTON |
The "Capture" button is pressed. | document-reader , camera-snapshot |
PRESS_CHANGE_CAMERA_BUTTON |
The "Change camera" button is pressed. | document-reader , camera-snapshot |
PRESS_MIRRORING_BUTTON |
The "Mirroring" button is pressed. | document-reader , camera-snapshot |
NEW_PAGE_AVAILABLE |
The document contains another page. | document-reader |
NEW_PAGE_STARTED |
Recognition of a new page has started. | document-reader |
CLOSE |
The "Close" button is pressed. | document-reader , camera-snapshot |
CAMERA_PROCESS_CLOSED |
The "Close" button is pressed on the document recognition screen. | document-reader , camera-snapshot |
CAMERA_PROCESS_STARTED |
Recognition from the camera has started. | document-reader |
VIDEO_STARTED |
Video stream started. | document-reader , camera-snapshot |
VIDEO_STOPPED |
Video stream stopped. | document-reader , camera-snapshot |
FILE_PROCESS_STARTED |
File processing has started. | document-reader , camera-snapshot |
PROCESS_FINISHED |
The component has finished its work. | document-reader , camera-snapshot |
SERVICE_INITIALIZED |
The component has started its work. | document-reader |
Action Data
1. In case of successful operation, the event.detail.data
field is structured as follows:
{
response: { ... },
status: 1
}
If video recording is enabled:
{
response: { ... },
status: 1,
video: Blob,
}
Available fields of event.detail.data
object:
* response
contains the object with resulting payload of the event's action execution.
* status
defines the status of event's action completion. For details, see action statuses.
* video
video of the document scanning process (if videoRecord
setting is set).
2. In case of event's action failure, the event.detail.data
field is structured as follows:
{
reason: 'CAMERA_PERMISSION_DENIED',
status: 0
}
Available fields of event.detail.data
object:
* reason
defines the reason of action's failure. For details, see failure reasons.
* status
defines the status of event's action completion. For details, see action statuses.
Action Statuses
Status | Description |
---|---|
0 | Failure |
1 | Success |
2 | Timeout |
Action Failure Reasons
Reason | Description of the reason |
---|---|
WASM_ERROR |
Error in WASM |
WASM_LICENSE |
Missing or incorrect license |
FILE_SIZE |
The file size is too large |
INCORRECT_FILE |
Problems with reading the file |
INCORRECT_SCENARIO |
Scenario is not supported |
MISSING_SCENARIO |
Scenario is missing |
UNKNOWN_ERROR |
Unknown error |
NOT_SUPPORTED |
The browser is not supported |
CAMERA_UNKNOWN_ERROR |
Unknown camera error |
CAMERA_PERMISSION_DENIED |
Access to the camera is prohibited |
NO_CAMERA |
There is no camera available |
INCORRECT_CAMERA_ID |
Camera with this ID was not found |
CONNECTION_ERROR |
Connection errors |
Event Generation Logic
The cases of event generation are described in the following table.
Event condition | Event type | Event object `event.detail` | Description |
---|---|---|---|
Component is mounted in the DOM. |
document-reader , camera-snapshot
|
|
To receive this event, you must wrap the component in another element (for example, a div) and add an addEventListener to it. When the component appears in the DOM, the event will pop up.
For example:
|
"From camera" button is pressed. |
document-reader , camera-snapshot
|
|
|
"From gallery" button is pressed. |
document-reader , camera-snapshot
|
|
|
"Retry" button is pressed. |
document-reader , camera-snapshot
|
|
|
"Skip page" button is pressed. |
document-reader
|
|
This event available only in document-reader .
|
"Capture" button is pressed. |
document-reader , camera-snapshot
|
|
|
"Change camera" button is pressed. |
document-reader , camera-snapshot
|
|
|
"Mirroring" button is pressed. |
document-reader , camera-snapshot
|
|
|
The document contains another page. |
document-reader
|
|
This event available only in document-reader .
|
Recognition of a new page has started. |
document-reader
|
|
This event available only in document-reader .
|
"Close" button is pressed. |
document-reader , camera-snapshot
|
|
|
"Close" button is pressed on the document recognition screen. |
document-reader , camera-snapshot
|
|
|
Recognition from the camera has started. |
document-reader , camera-snapshot
|
|
|
Video stream has started. |
document-reader , camera-snapshot
|
|
|
Video stream has stopped. |
document-reader , camera-snapshot
|
|
|
File processing has started. |
document-reader , camera-snapshot
|
|
|
The work of the component is completed successfully. |
document-reader , camera-snapshot
|
|
|
The work of the component is completed by timeout. |
document-reader
|
|
This event available only in document-reader .
|
The work of the component failed. |
document-reader , camera-snapshot
|
|
|
Component is initialized and ready to work. |
document-reader
|
|
This event available only in document-reader .
|
Event Response
You can get the response of the component's event in the detail.data.response
field of the event object. For example:
const component = document.querySelector('document-reader');
function listener(event) {
if (event.detail.action === 'PROCESS_FINISHED' && event.detail.data.status === 1) {
const response = event.detail.data.response;
console.log(response);
}
}
component.addEventListener('document-reader', listener);
To get the results of processing of each frame, you can set the callback function as in the following example:
window.RegulaDocumentSDK.recognizeListener = (response) => console.log(response);
Settings and Attributes
There are two ways to define the element's settings: using the settings
property of the JavaScript object or using attributes of the HTML tag.
See the description and examples below.
-
Using
settings
property to configure element:const element = document.createElement('document-reader'); element.settings = { startScreen: true, internalScenario: 'Locate', multipageProcessing: true, };
-
Using attributes to configure element:
<document-reader start-screen internal-scenario="Locate"></document-reader>
We recommend using the settings
property of the element to configure its parameters.
This method gives more flexibility in setup, in addition, all new parameters in the future will be available only as the settings of the object (not as HTML attributes).
See all component's settings and attributes in the following table.
Setting name | Attribute name | Description | Data type | Default value | Values | Available in |
---|---|---|---|---|---|---|
locale | locale | The language of the component interface. If empty, the language is selected from the browser settings, if it is not found, the system language is taken. | string | en |
ru , en , de , pl , it , hu , zh , sk , uk , fr , es , pt , ar , nl , id , vi , ko , ms , ro , el , tr , ja , cs , th , hi , bn , he , fi , sv , da , hr , no |
document-reader , camera-snapshot |
internalScenario | internal-scenario | The component document verification scenario. | string | MrzAndLocate |
MrzAndLocate , MrzOrLocate , Mrz , Locate , Barcode , MrzOrBarcode , BarcodeAndLocate |
document-reader |
multipageProcessing | multipage-processing | Whether to allow processing of two pages in cases when the component detects an ID1-sized document. Multipage processing is not triggered for documents of other formats. If true , the component asks for the second page and processes it. If false , only one page/side of the document is processed regardless the document format. |
boolean | false |
true , false |
document-reader |
startScreen | start-screen | Whether to show the start screen with two options for the document image uploading: From camera and From gallery. If true , the start screen is shown. If false , no start screen is shown and instead the camera of the device is turned on automatically to capture the image of the document. |
boolean | false |
true , false |
document-reader , camera-snapshot |
multipleFileInput | multiple | Whether to allow uploading more than one file via the file system. Can be set to true only if startScreen is true . |
boolean | true |
true , false |
document-reader , camera-snapshot |
cameraId | camera-id | Ability to select a camera. You can get the device ID using navigator.mediaDevices.enumerateDevices(). | string | undefined |
camera id string value |
document-reader , camera-snapshot |
devLicense | license | To use the component on test environments, set the base64 license value to the license attribute. |
string | undefined |
base64 license value |
document-reader |
regulaLogo | copyright | Show Regula copyright footer. | boolean | true |
true , false |
document-reader , camera-snapshot |
changeCameraButton | change-camera | Show the camera switch button. | boolean | false |
true , false |
document-reader , camera-snapshot |
closeButton | close-button | Show the close button. | boolean | true |
true , false |
document-reader , camera-snapshot |
captureButton | capture-button | Show the capture button. | boolean | true |
true , false |
document-reader |
skipButton | Show the skip button for the second page. | boolean | true |
true , false |
document-reader |
|
captureMode | Sets the capture mode. Mode auto - recognition starts immediately after the camera starts working. Mode captureFrame - recognition of the frame received after pressing the capture button. Mode captureVideo - recognition begins after pressing the button, pressing the button again will send the received frame for processing. |
string | auto |
auto , captureVideo , captureFrame |
document-reader |
|
resolution | Sets the resolution of the video stream from the camera. | object | { width: 1920, height: 1080 } |
{ width: number, height: number } |
document-reader , camera-snapshot |
|
cameraMode | Selects the front or rear camera of the device. | object | environment |
environment , user |
document-reader , camera-snapshot |
|
flipFrontIcon | Sets the front side of the document flip icon. You can set link (https://example.link.com/icon.png ), image in base64 string (data:image/svg+xml;base64,PHN2ZyBjbGF... ) or imported image if you use module bundler. |
string | undefined |
link to image , base64 string , imported image |
document-reader |
|
flipBackIcon | Sets the back side of the document flip icon. You can set link (https://example.link.com/icon.png ), image in base64 string (data:image/svg+xml;base64,PHN2ZyBjbGF... ) or imported image if you use module bundler. |
string | undefined |
link to image , base64 string , imported image |
document-reader |
|
cameraFrameBorderWidth | Sets the thickness of the document capture frame. | number | 5 | any number |
document-reader |
|
backgroundMaskAlpha | Sets the transparency of the background outside the frame. | number | 0.5 | from 0 to 1 |
document-reader |
|
cameraFrameLandscapeAspectRatio | Sets the aspect ratio of the capture frame for landscape mode. | number | depends on the scenario | any number |
document-reader |
|
cameraFramePortraitAspectRatio | Sets the aspect ratio of the capture frame for portrait mode. | number | depends on the scenario | any number |
document-reader |
|
statusIcon | Show status icon. | boolean | true |
true , false |
document-reader |
|
statusPositionMultiplier | Sets the vertical position of the status message. | number | undefined |
from 0 to 2 |
document-reader |
|
cameraFrameOffsetWidth | Sets the offset of the capture frame. | number | undefined |
any number |
document-reader |
|
cameraFrameVerticalPositionMultiplier | Sets the offset of the capture frame from the top edge. | number | undefined |
from 0 to 2 |
document-reader |
|
cameraFrameShapeType | Sets the capture frame shape type. | string | line |
line , corners |
document-reader |
|
cameraFrameLineCap | Sets the style of the end of the capture frame line when cameraFrameShapeType='corners' |
string | butt |
butt , round , square |
document-reader |
|
cameraFrameLineLength | Sets the length of the capture frame line when cameraFrameShapeType='corners' |
number | 5 | any number |
document-reader |
|
cameraFrameCornerRadius | Sets the radius of rounding of the capture frame. | number | 15 | any number |
document-reader |
|
cameraFrameDefaultColor | Sets the color of the capture frame. | string | rgba(255, 255, 255, 0.9) |
any color string |
document-reader |
|
cameraFrameActiveColor | Sets the capture frame color when a document is detected. | string | rgba(30, 130, 76, 0.9) |
any color string |
document-reader |
|
statusTextColor | Sets the color of the text message status. | string | white |
any color string |
document-reader , camera-snapshot |
|
statusBackgroundColor | Sets the background color of the message status. | string | rgba(27, 16, 31, 0.5) |
any color string |
document-reader , camera-snapshot |
|
cameraFrame | Show the capture frame. | boolean | true |
true , false |
document-reader |
|
captureButtonDelay | Show the capture button after delay. | number | undefined |
any number |
document-reader |
|
nonce | Sets the unique nonce value to maintain the CSP policy. | string | undefined |
unique nonce value |
document-reader , camera-snapshot |
|
videoRecord | Sets the ability to record a video of the document scanning process. If set to true it records the entire process. You can also set the recording delay and recording duration. The video will be available in the component response. | boolean or object | undefined |
true , false , { delay: number, duration: number } |
document-reader |
|
videoCaptureMotionControl | Enables device shaking control. | boolean | false |
true , false |
document-reader |
Backend reprocessing
You can send the results to the backend for further processing:
1. Set backendProcessing
, serviceURL
and httpHeaders
(optional) in processParam:
window.RegulaDocumentSDK.recognizerProcessParam = {
processParam: {
backendProcessing: {
serviceURL: 'YOUR_SERVICE_URL',
httpHeaders: { // you can set http headers if necessary
key1: 'header1',
key2: 'header2',
key3: 'header3'
}
}
},
};
const component = document.querySelector('document-reader');
function listener(event) {
if (event.detail.action === 'PROCESS_FINISHED' && event.detail.data.status === 1) {
window.RegulaDocumentSDK.finalizePackage();
}
}
component.addEventListener('document-reader', listener);
Appearance Customization
Font and Colors
Using CSS variables, you can change the font and the main colors of the components. See the table for the details.
Variable | Info | Default value |
---|---|---|
--font-family | The font family of all text elements. If you change the font family, make sure to adjust the font size so the message on the start screen would fit the frame. | Noto Sans, sans-serif |
--font-size | The font size for the text elements. | 16px |
--main-color | Color for the graphic elements of the component. By default, the brand Regula violet is set. | #bd7dff |
--hover-color | Buttons hover color. | #c994ff |
--active-color | Buttons active color. | #bd7dff |
The following example demonstrates the document-reader
HTML element font and color customization via the custom CSS class:
CSS:
.my-custom-style {
--font-family: Arial, sans-serif;
--main-color: green;
}
HTML:
<document-reader class="my-custom-style"></document-reader>
Localized Messages
To change the standard component messages or any text, specify the language attribute (see locale
in settings and attributes) to be used.
You can select one from existing locales or add your custom one. See the following example:
const element = document.createElement('document-reader');
element.translations = {
en: {
fromCamera: 'Use your camera',
},
};
body.append(element);
Note: To see the changes applied, don't forget to set the desired language to the locale
attribute.
<document-reader locale="en"></document-reader>
See the following table with localized labels, used in the components.
Label | Default message in en locale |
Used in |
---|---|---|
success | Success! | document-reader , camera-snapshot |
fileCorrupt | This file is corrupt or not supported | document-reader , camera-snapshot |
selectAnotherFile | Please select another file | document-reader , camera-snapshot |
error | Error! | document-reader , camera-snapshot |
somethingWentWrong | Something went wrong | document-reader , camera-snapshot |
tryAgain | Try again | document-reader , camera-snapshot |
fromCamera | From camera | document-reader , camera-snapshot |
fromGallery | From gallery | document-reader , camera-snapshot |
cameraUnavailable | Camera unavailable! | document-reader , camera-snapshot |
preparingCamera | Preparing the camera... | document-reader , camera-snapshot |
noCameraAvailable | No camera available | document-reader , camera-snapshot |
incorrectCameraId | No camera with the specified ID found. | document-reader , camera-snapshot |
allowAccessToCamera | Allow access to the camera and reload this page to continue. | document-reader , camera-snapshot |
cameraConnection | Make sure the camera is connected correctly. | document-reader , camera-snapshot |
checkCameraId | Check if the specified camera ID is correct. | document-reader , camera-snapshot |
scanIDInBrowser | Scan an ID in your browser | document-reader |
useYourDeviceCamera | Use your device camera to scan a document or select a photo of the document from the gallery | document-reader |
processingFinished | Processing finished. | document-reader |
largeFile | This file is too large to be uploaded | document-reader |
selectSmallerFile | Please select a smaller file | document-reader |
versionNotSupported | Your browser version is not supported | document-reader |
updateBrowser | Update your browser version | document-reader |
licenseError | A license error has occurred | document-reader |
licenseExpired | The license cannot be found or has expired | document-reader |
timeout | Timeout | document-reader |
processing | Processing... | document-reader |
preparingService | Preparing the service... | document-reader |
placeDocumentIntoFrame | Fit the document into the frame | document-reader |
noFocus | No camera focus | document-reader |
moveCloser | Move closer | document-reader |
glaresOnDocument | Avoid glare on the document | document-reader |
holdDocumentStraight | Hold the document straight | document-reader |
documentProcessing | Document processing... | document-reader |
flipDocument | Flip the document | document-reader |
verified | Verified! | document-reader |
keepDeviceStill | Hold the device still | document-reader |
positionDocumentCenter | Position the document in the center | camera-snapshot |
photoCapturedSuccessfully | The photo is captured successfully. | camera-snapshot |
uploadPhoto | Upload a photo | camera-snapshot |
useCameraOrGallery | Use your device camera or select a photo from the gallery | camera-snapshot |
Document Reader Processor
DocumentReaderProcessor manages the document image recognition and other related operations, leaving implementation of UI to you.
npm Processor Integration
Step 1. Install the package @regulaforensics/vp-frontend-document-components
:
npm i @regulaforensics/vp-frontend-document-components
Step 2. Import the class DocumentReaderProcessor
into your .js
file.
Using module bundler:
import { DocumentReaderProcessor } from '@regulaforensics/vp-frontend-document-components';
Without module bundler:
import { DocumentReaderProcessor } from '/node_modules/@regulaforensics/vp-frontend-document-components/dist/main.js';
Step 3. Add a video tag to the .html
file, then prepare and initialize DocumentReaderProcessor
.
const videoElement = document.getElementById('yourVideoElement');
const processor = new DocumentReaderProcessor(videoElement);
processor.recognizerProcessParam = {
processParam: {
scenario: 'MrzAndLocate',
},
};
processor.imageProcessParam = {
processParam: {
scenario: 'MrzAndLocate',
},
};
try {
// Variant 1 - for production environment
await processor.initialize();
// Variant 2 - for test-only environment
// await processor.initialize({ license: 'BASE64_LICENSE_KEY' });
const result = await processor.startRecognition();
processor.stopRecognition();
console.log(result);
} catch (e) {
console.log(e);
}
In the preceding example, the DocumentReaderProcessor
object is created using the HTML element with the ID yourVideoElement
.
After that, processor
needs to be initialized. There are two licensing variants:
1. Domain name licensing (for production environment).
To get your website domain licensed, contact our sales team.
Then asynchronously call the initialize
method without parameters:
await processor.initialize();
2. Base64 license string (for test-only environment).
Convert Regula license file to the Base64 string and then asynchronously call initialize
method, replacing BASE64_LICENSE_KEY
with your encoded string:
await processor.initialize({ license: 'BASE64_LICENSE_KEY' });
For more information about licensing, see the Document Reader SDK Licensing page and the How to Convert a License File to BASE64 FAQ article.
CDN Processor Integration
Step 1. Connect the script to your .html
file.
Use the CDN link in a format as follows: unpkg.com/:package@:version/:file
For example:
<script src="https://unpkg.com/@regulaforensics/vp-frontend-document-components@latest/dist/main.iife.js"></script>
Note: You can find all available script versions in the corresponding section of npm, using the same link from the previous example.
Step 2. Add a video tag to the .html
file, then prepare and initialize DocumentReaderProcessor
.
DocumentReaderProcessor
is available in the global variable window.Regula
. See the following example:
const { DocumentReaderProcessor } = window.Regula;
const videoElement = document.getElementById('yourVideoElement');
const processor = new DocumentReaderProcessor(videoElement);
processor.recognizerProcessParam = {
processParam: {
scenario: 'MrzAndLocate',
},
};
processor.imageProcessParam = {
processParam: {
scenario: 'MrzAndLocate',
},
};
try {
// Variant 1 - for production environment
await processor.initialize();
// Variant 2 - for test-only environment
// await processor.initialize({ license: 'BASE64_LICENSE_KEY' });
const result = await processor.startRecognition(); // Result of the document recognition will be located here.
processor.stopRecognition();
console.log(result);
} catch (e) {
console.log(e);
}
In the preceding example, the DocumentReaderProcessor
object is created using the HTML element with ID yourVideoElement
.
After that, processor
needs to be initialized with the license. There are two licensing variants:
1. Domain name licensing (for production environment).
To get your website domain licensed, contact our sales team.
Then asynchronously call the initialize
method without parameters:
await processor.initialize();
2. Base64 license string (for test-only environment).
You need to convert Regula license file to the Base64 string and then asynchronously call initialize
method, replacing BASE64_LICENSE_KEY
with that encoded string:
await processor.initialize({ license: 'BASE64_LICENSE_KEY' });
For more information about licensing, see the Document Reader SDK Licensing page and the How to Convert a License File to BASE64 FAQ article.
Processor Methods
initialize
Initializes the DocumentReaderProcessor object. Accepts an object with a Base64 encoded license string.
Note: Base64 license string is applied only to test environments, production mode must use the domain name licensing.
await processor.initialize({ license: 'BASE64_LICENSE_KEY' });
startRecognition
Launches the video stream and starts recognizing the document. Returns the result of document processing.
const result = await processor.startRecognition();
startRecognition
may take the callback function with the object parameter currentPage
holding the data of the page currently being processed.
The currentpage
data fields include:
currentPage.data
object with an intermediate processing resultcurrentPage.startNextPage
method for starting the next page processioncurrentPage.finishRecognition
method for completing the entire process
The next example demonstrates the case, when recognition of the next page is delayed by 3 seconds (3000 ms). During this time you may ask the user to turn the document over.
async function pageListener(currentPage) {
setTimeout(async () => {
await currentPage.startNextPage();
}, 3000);
}
const result = await processor.startRecognition(pageListener);
processImage
Processes the image files, containing documents. Can take as a parameter a FileList
or Blob
array:
const file = 'FileList or Blob array';
const result = await processor.processImage(file);
Note: For more information about FileList and Blob types, see the links: FileList and Blob.
switchCamera
Switches to the next camera (in case there are several available).
await processor.switchCamera();
stopRecognition
Stops the document recognition process and ends the video stream.
processor.stopRecognition();
Processor Parameters
You can change the default settings for video streaming and document recognition.
The settings must be set before the document recognition process starts.
streamParam
The video stream parameters.
processor.streamParam = {
cameraMode: 'environment',
preferredCameraId: '',
resolution: {
width: 1280,
height: 720,
},
}
Available streaming parameters:
cameraMode
Camera facing mode. Can have values of 'environment' (by default) or 'user'.preferredCameraId
ID of the concrete camera to be used for the streaming. Can be extracted fromnavigator.mediaDevices.enumerateDevices()
. Not set by default.resolution
Resolution of a video stream. 1280 x 720 by default.
recognizerProcessParam
The parameters for recognizing a document from the camera (by the startRecognition
method). See the following example with several parameters and their default values:
processor.recognizerProcessParam = {
processParam: {
returnUncroppedImage: true,
returnPackageForReprocess: false,
},
};
For more information, see the list of all available document processing params.
imageProcessParam
The settings for recognizing an image as a document file (by processImage
method).
See the following example with several parameters and their default values:
// Default settings:
processor.imageProcessParam = {
processParam: {
returnUncroppedImage: true,
returnPackageForReprocess: false,
},
}
For more information, see the list of all available document processing params.
recognizeListener
The callback function that takes as a parameter the processing result for each frame (response
).
See the following example, where the processing result for each frame is logged to the console:
function listener(response) {
console.log(response);
}
processor.recognizeListener = listener;
Note: The listener for image recognizer is not set by default.
videoElement
The HTML element to display the video stream from the camera.
This setting changes the video element that was defined during processor object construction new DocumentReaderProcessor(videoElement)
.
See the example:
const videoElement = document.getElementById('HTMLVideoElement');
processor.videoElement = videoElement; // null by default
By default, processor.videoElement
has null
value.
isInitialized
Read-only property. true
if the processor has been initialized.
processor.isInitialized;
isProcessing
Read-only property. true
if document recognition is still in progress.
processor.isProcessing;
Package Resources
Document reader requires WASM (ProcMgr.wasm
, ProcMgr.data
) and worker (ProcMgr.worker.js
) files to work.
By default, these files are downloaded from Regula servers, but you can set your own source.
1. To download these files from our server to local machine, you can get the link in the window.RegulaDocumentSDK.workerPath
field.
2. Then, in the ProcMgr.worker.js
file, use the search to find https://wasm.regulaforensics.com
and replace the full link with your custom URL.
Upload all three files (ProcMgr.worker.js
, ProcMgr.wasm
, ProcMgr.data
) to the location you specified. Also, change the address in windows.RegulaDocumentSDK
.
For Predefined UI Components:
window.RegulaDocumentSDK.workerPath = 'https://custom-wasm-and-worker-files-path.com';
For Document Reader Processor:
const processor = new DocumentReaderProcessor(videoElement);
processor.workerPath = 'https://custom-wasm-and-worker-files-path.com';
In the given examples, change the workerPath
parameter value to your custom source URL.
Attention! The files must be located in the same directory and have the same names as were previously specified.
Potential Problems
UI components and SDK use the getUserMedia
method to display the video stream from the camera. This feature is available only in secure contexts (HTTPS).
Examples
You can see the examples of using the components on the Samples page.
Additional Resources
The Document Reader web components are also available on Storybook.
FAQ
How do I collect logs?
Logging can be helpful when you run into any issues. Logs contain information about how you use our products. That data helps Regula stuff to analyze and troubleshoot the cases you may experience.
There are two ways to output logs: console or function callback.
Console
To initiate the process of logs collecting:
1. Open the Developer menu in your browser.
2. Go to the Console tab.
3. In Console, enter the following line:
localStorage.logger = 'main,wasm>console'
4. Reload the page.
5. Add the log
setting to the processParam
if you want to see logs from WASM:
{
"processParam": {
"log": true
}
}
6. Start image processing. Logs will be displayed in Console.
Function callback
1. Import logging service from library.
import { Logger } from '@regulaforensics/vp-frontend-document-components';
2. Set the callback function.
Logger.logListener = (log) => {
// ...
// do something with log
// ...
};
3. Add the log
setting to the processParam
if you want to see logs from WASM:
{
"processParam": {
"log": true
}
}