Security News
RubyGems.org Adds New Maintainer Role
RubyGems.org has added a new "maintainer" role that allows for publishing new versions of gems. This new permission type is aimed at improving security for gem owners and the service overall.
@regulaforensics/vp-frontend-document-components
Advanced tools
Regula framework agnostic web components to work with webcamera
The Document Reader Web Components let you add document verification to your website, including the features:
The Document Reader Web Components package contains:
document-reader
for documents recognition, camera-snapshot
for capturing images from a camera or uploading from a gallery.Current document acts as a quick start guide for operating Document Reader Web Components and as a reference to their main processing parameters.
Important notes:
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.
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';
Without module bundler:
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',
},
};
2. Define the components and initialize the service:
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>
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;
2. 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',
},
};
3. Define the components and initialize the service.
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.
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,
},
},
},
};
Session ID for video processing:
window.RegulaDocumentSDK.recognizerProcessParam = {
tag: 'your session id',
};
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',
};
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 |
timeoutFromFirstDetect | Start the countdown from the moment the document is detected. | number | 5000 | 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. | |||
expectedPass | Activated image quality checks. | string[] | ['dpiThreshold', 'glaresCheck', 'focusCheck'] | 'dpiThreshold', 'glaresCheck', 'focusCheck' |
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 |
glaresCheck | This option enables glares check while performing image quality validation. | boolean | true | true , false |
glaresCheckParams | Settings for glare check. | |||
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 |
respectImageQuality | When enabled, image quality checks status affects document optical and overall status. | 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 |
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 | 0 - 1 |
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 | true , false |
Attention! If the multipage-processing
or internal-scenario
attributes are set, the corresponding multipageProcessing
and scenario
parameters' values are ignored.
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.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 "Camera" button is pressed. | document-reader , camera-snapshot |
PRESS_FILE_BUTTON | The "Files" 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_REMOTE_DEVICE_BUTTON | The "Mobile device" button is pressed. | document-reader |
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 |
REMOTE_TRANSACTION_UPLOADED | Remote transaction with current tag was uploaded | document-reader |
REMOTE_PROCESS_FINISHED | Remote transaction with current tag was processed | document-reader |
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.Status | Description |
---|---|
0 | Failure |
1 | Success |
2 | Timeout |
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 |
HTTP_NOT_SUPPORTED | The web component does not work over the http protocol |
INSECURE_PAGE_CONTEXT | The web component does not work in insecure context |
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 |
BAD_CONFIGURATION | Incompatible component settings are installed |
1. In case of remote scan scenario REMOTE_TRANSACTION_UPLOADED event.detail
will contain the following data:
{
action: EventActions.REMOTE_TRANSACTION_UPLOADED,
data: {
id: 1,
state: 1,
updatedAt: 'dateStr'
},
}
Transaction id can be used to trigger reprocessing.
The cases of event generation are described in the following table.
Event condition | Event type |
Event object | Description |
---|---|---|---|
Component is mounted in the DOM. |
|
|
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:
|
"Camera" button is pressed. |
|
| |
"Files" button is pressed. |
|
| |
"Retry" button is pressed. |
|
| |
"Skip page" button is pressed. |
|
|
This event available only in |
"Capture" button is pressed. |
|
| |
"Change camera" button is pressed. |
|
| |
"Mobile device" button is pressed. |
|
| |
"Mirroring" button is pressed. |
|
| |
The document contains another page. |
|
|
This event available only in |
Recognition of a new page has started. |
|
|
This event available only in |
"Close" button is pressed. |
|
| |
"Close" button is pressed on the document recognition screen. |
|
| |
Recognition from the camera has started. |
|
| |
Video stream has started. |
|
| |
Video stream has stopped. |
|
| |
File processing has started. |
|
| |
The work of the component is completed successfully. |
|
| |
The work of the component is completed by timeout. |
|
|
This event available only in |
The work of the component failed. |
|
| |
Component is initialized and ready to work. |
|
|
This event available only in |
The transaction has been successfully uploaded from the delegated device. |
|
|
This event available only in |
Remote processing has been completed successfully. |
|
|
This event available only in |
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);
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.
settings
property to configure element:const element = document.createElement('document-reader');
element.settings = {
startScreen: true,
internalScenario: 'Locate',
multipageProcessing: true,
};
<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, bitrate: number } | document-reader | |
videoCaptureMotionControl | Enables device shaking control. | boolean | false | true , false | document-reader | |
fromCameraButton | Show the camera button. | boolean | true | true , false | document-reader , camera-snapshot | |
uploadFileButton | Show the files button. | boolean | true | true , false | document-reader , camera-snapshot | |
mirrorButton | Show the mirroring button. | boolean | false | true , false | document-reader , camera-snapshot | |
mirrorType | Sets the initial value of video mirroring. | string | mirror - for front camera, noMirror - for back camera, | mirror , noMirror | document-reader , camera-snapshot | |
mobileDelegate | Changes the success screen in case of delegating scanning via a mobile device. | boolean | false | true , false | document-reader |
You can send the results to the backend for further processing:
1. Set backendProcessing
, serviceURL
and httpHeaders
(optional) in processParam:
window.RegulaDocumentSDK.recognizerProcessParam = {
processParam: {
scenario: InternalScenarios.MrzAndLocate,
backendProcessing: {
serviceURL: 'YOUR_SERVICE_URL',
httpHeaders: { // you can set http headers if necessary
key1: 'header1',
key2: 'header2',
key3: 'header3'
}
}
},
};
2. Send the data to the backend after receiving the processing results:
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);
For cases when user's main device lacks camera or does not succeed to scan with given camera quality, you have an option to delegate scanning to another available device (i.e. phone).
processor.recognizerProcessParam = {
processParam: {
scenario: InternalScenarios.MrzAndLocate,
},
delegateProcessing: {
delegateURL: 'https://your-page.com?tag={tag}', // the page which will be used by other device
serviceURL: 'https://my-service.com', // your backend service
httpHeaders: { // http headers if needed
header: 'value'
}
},
tag: 123 // your session id, will be added to delegateURL in place of {tag} substring
}
https://your-page.com?tag=123
)processor.recognizerProcessParam = {
tag: new URL(window.location.href).searchParams.get('tag') // assume session Id tag was added to URL params
}
element.settings = {
startScreen: false, // From camera recognition is expected
mobileDelegate: true
}
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. | #7E57C5 |
--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>
document-reader and camera-snapshot components have width and height set to 100% by default and therefore try to fit their container element. This should not affect correct CSS Grid positioning, but for Flexbox make sure to style document-reader dimensions and set flex-basis, i.e.:
document-reader.flex-item {
width: auto;
height: auto;
flex-basis: 500px; // distinct width of your choice
}
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 |
---|---|---|
done | Done! | document-reader , camera-snapshot |
fileCorrupt | This file is corrupt or not supported | document-reader , camera-snapshot |
somethingWentWrong | Something went wrong | document-reader , camera-snapshot |
tryAgain | Try again | 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 |
gallery | Gallery | document-reader , camera-snapshot |
files | Files | document-reader , camera-snapshot |
camera | Camera | document-reader , camera-snapshot |
largeFile | This file is too large to be uploaded | document-reader |
versionNotSupported | Your browser version is not supported | document-reader |
httpNotSupported | HTTPS is not used | document-reader |
insecurePageContext | Insecure page context | document-reader |
timeout | Timeout | 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 |
keepDeviceStill | Hold the device still | document-reader |
positionDocumentCenter | Position the document in the center | camera-snapshot |
uploadPhoto | Upload a photo | camera-snapshot |
switchToMobile | Switch to mobile | document-reader |
openPhoneCamera | Open the camera on your mobile device, scan the QR code, and follow the link | document-reader |
pleaseWait | Please wait... | document-reader |
mobileDevice | Mobile device | document-reader |
verifyYourIdentity | Verify your identity document | document-reader |
fromCameraFilesMobileDesktop | Capture a document using the computer’s camera, or upload it from files, or scan it on a mobile device | document-reader |
fromCameraGalleryMobile | Capture a document using the computer’s camera, or upload it from gallery | document-reader |
badLicense | The license cannot be found or has expired | document-reader |
fromCameraFilesDesktop | Capture a document using the computer’s camera, or upload it from files | document-reader |
fromCameraMobileDesktop | Capture a document using the computer’s camera, or scan it on a mobile device | document-reader |
fromFilesMobileDesktop | Upload a document from files, or scan it on a mobile device | document-reader |
fromCameraDesktop | Use the computer's camera to capture a document | document-reader |
fromFilesDesktop | Pick a document from the files and upload it | document-reader |
fromMobileDesktop | Use your mobile camera to capture a document | document-reader |
fromGalleryMobile | Pick a document from the gallery and upload it | document-reader |
returnToComputer | Return to the computer | document-reader |
documentCaptured | Your document has been captured | document-reader |
DocumentReaderProcessor manages the document image recognition and other related operations, leaving implementation of UI to you.
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.
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.
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' });
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 processThe 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);
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.
Switches to the next camera (in case there are several available).
await processor.switchCamera();
Stops the document recognition process and ends the video stream.
processor.stopRecognition();
You can change the default settings for video streaming and document recognition.
The settings must be set before the document recognition process starts.
The video stream parameters.
processor.streamParam = {
cameraMode: 'environment',
preferredCameraId: '',
resolution: {
width: 1280,
height: 720,
},
}
Available streaming parameters:
cameraMode
preferredCameraId
navigator.mediaDevices.enumerateDevices()
. Not set by default.resolution
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.
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.
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.
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.
Read-only property. true
if the processor has been initialized.
processor.isInitialized;
Read-only property. true
if document recognition is still in progress.
processor.isProcessing;
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. 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.
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).
You can see the examples of using the components on the Samples page.
The Document Reader web components are also available on Storybook.
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.
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.
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
}
}
FAQs
Regula framework agnostic web components to work with webcamera
The npm package @regulaforensics/vp-frontend-document-components receives a total of 1,971 weekly downloads. As such, @regulaforensics/vp-frontend-document-components popularity was classified as popular.
We found that @regulaforensics/vp-frontend-document-components demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 0 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
RubyGems.org has added a new "maintainer" role that allows for publishing new versions of gems. This new permission type is aimed at improving security for gem owners and the service overall.
Security News
Node.js will be enforcing stricter semver-major PR policies a month before major releases to enhance stability and ensure reliable release candidates.
Security News
Research
Socket's threat research team has detected five malicious npm packages targeting Roblox developers, deploying malware to steal credentials and personal data.