Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@regulaforensics/vp-frontend-document-components

Package Overview
Dependencies
Maintainers
0
Versions
261
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@regulaforensics/vp-frontend-document-components

Regula framework agnostic web components to work with webcamera

  • 7.5.1940-nightly
  • npm
  • Socket score

Version published
Weekly downloads
2.3K
decreased by-27.53%
Maintainers
0
Weekly downloads
 
Created
Source

Document Reader Web Components


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 it, and parse into text text fields
  • Read barcodes, and parse them into 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 are document-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

DevicesChromeFireFoxSafari
Mobile (iOS)999911
Mobile (Android)6663-
Desktop616311

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';

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>

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;

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.

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,
      },
    },
  },
};

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',
};
Parameters Description
SettingInfoData typeDefault valueValues
returnUncroppedImageWhen enabled, returns input images in output.booleantruetrue, false
scenarioRecognition scenario.string'MrzAndLocate''MrzAndLocate', 'MrzOrLocate', 'Mrz', 'Locate'
multipageProcessingWhether to enable multi-page document processing mode.booleantruetrue, false
timeoutRecognition timeout in milliseconds. After this time process will be finished.number2000numbers > 0
timeoutFromFirstDetectStart the countdown from the moment the document is detected.number5000numbers > 0
resultTypeOutputTypes 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
returnPackageForReprocessWhen enabled, returns the package for reprocessing on the backend.booleanfalsetrue, false
imageQaWhen enabled, image quality checks status affects document optical and overall status.
expectedPassActivated image quality checks.string[]['dpiThreshold', 'glaresCheck', 'focusCheck']'dpiThreshold', 'glaresCheck', 'focusCheck'
dpiThresholdThis parameter sets threshold for Image QA check of the presented document physical dpi. If actual document dpi is below this threshold, check will fail.number150numbers > 0
glaresCheckThis option enables glares check while performing image quality validation.booleantruetrue, false
glaresCheckParamsSettings for glare check.
imageOutputMaxHeightThis 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.number0numbers > 0
imageOutputMaxWidthThis 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.number0numbers > 0
fieldTypesFilterList of text field types to extract. If empty, all text fields from template will be extracted. Narrowing the list can shorten processing time.number[][]
dateFormatThis 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'
measureSystemThis option allows you to set the system of measurement used for converting original values in document to output result values. Metric by default.number00 - Metric, 1 - Imperial
imageDpiOutMaxThis 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.numbernumbers > 0
alreadyCroppedThis 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.booleanfalsetrue, false
customParamsThis 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.booleantruetrue, false
updateOCRValidityByGlareWhen enabled, fail OCR field validity, if there is a glare over the text field on the image.booleanfalsetrue, false
returnCroppedBarcodeWhen enabled, returns cropped barcode images for unknown documents.booleanfalsetrue, false
respectImageQualityWhen enabled, image quality checks status affects document optical and overall status.booleanfalsetrue, false
forceDocFormatForce use of specified document format when locating and recognizing document to reduce the number of candidates.number0 - 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...
noGraphicsWhen enabled, no graphic fields will be cropped from document image.booleanfalsetrue, false
documentAreaMinSpecifies 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.number00 - 1
depersonalizeLogWhen enabled, all personal data will be forcibly removed from the logs.booleanfalsetrue, false
multiDocOnImageThis option allows locating and cropping multiple documents from one image if enabled.booleanfalsetrue, false
shiftExpiryDateThis 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.number0numbers > 0
minimalHolderAgeThis options allows specifying the minimal age in years of the document holder for the document to be considered valid.number0numbers > 0
mrzFormatsFilterThis 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
forceReadMrzBeforeLocateWhen 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.booleanfalsetrue, false
parseBarcodesThis option can be disabled to stop parsing after barcode is read.booleantruetrue, false
splitNamesWhen 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.booleanfalsetrue, false
backendProcessingWhen 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', ... } }
generateNumericCodesThis parameter is used to generate numeric representation for issuing state and nationality codes.booleantrue, 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 actionDescription of the actionComponents and events, where present
ELEMENT_VISIBLEComponent is appended in the DOM.document-reader, camera-snapshot
PRESS_CAMERA_BUTTONThe "Camera" button is pressed.document-reader, camera-snapshot
PRESS_FILE_BUTTONThe "Files" button is pressed.document-reader, camera-snapshot
PRESS_RETRY_BUTTONThe "Retry" button is pressed.document-reader, camera-snapshot
PRESS_SKIP_BUTTONThe "Skip" button is pressed.document-reader
PRESS_CAPTURE_BUTTONThe "Capture" button is pressed.document-reader, camera-snapshot
PRESS_CHANGE_CAMERA_BUTTONThe "Change camera" button is pressed.document-reader, camera-snapshot
PRESS_REMOTE_DEVICE_BUTTONThe "Mobile device" button is pressed.document-reader
PRESS_MIRRORING_BUTTONThe "Mirroring" button is pressed.document-reader, camera-snapshot
NEW_PAGE_AVAILABLEThe document contains another page.document-reader
NEW_PAGE_STARTEDRecognition of a new page has started.document-reader
CLOSEThe "Close" button is pressed.document-reader, camera-snapshot
CAMERA_PROCESS_CLOSEDThe "Close" button is pressed on the document recognition screen.document-reader, camera-snapshot
CAMERA_PROCESS_STARTEDRecognition from the camera has started.document-reader
VIDEO_STARTEDVideo stream started.document-reader, camera-snapshot
VIDEO_STOPPEDVideo stream stopped.document-reader, camera-snapshot
FILE_PROCESS_STARTEDFile processing has started.document-reader, camera-snapshot
PROCESS_FINISHEDThe component has finished its work.document-reader, camera-snapshot
SERVICE_INITIALIZEDThe component has started its work.document-reader
REMOTE_TRANSACTION_UPLOADEDRemote transaction with current tag was uploadeddocument-reader
REMOTE_PROCESS_FINISHEDRemote transaction with current tag was processeddocument-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
StatusDescription
0Failure
1Success
2Timeout
Action Failure Reasons
ReasonDescription of the reason
WASM_ERRORError in WASM
WASM_LICENSEMissing or incorrect license
FILE_SIZEThe file size is too large
INCORRECT_FILEProblems with reading the file
INCORRECT_SCENARIOScenario is not supported
MISSING_SCENARIOScenario is missing
UNKNOWN_ERRORUnknown error
NOT_SUPPORTEDThe browser is not supported
HTTP_NOT_SUPPORTEDThe web component does not work over the http protocol
INSECURE_PAGE_CONTEXTThe web component does not work in insecure context
CAMERA_UNKNOWN_ERRORUnknown camera error
CAMERA_PERMISSION_DENIEDAccess to the camera is prohibited
NO_CAMERAThere is no camera available
INCORRECT_CAMERA_IDCamera with this ID was not found
CONNECTION_ERRORConnection errors
BAD_CONFIGURATIONIncompatible component settings are installed
Remote action data

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.

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

{
  action: 'ELEMENT_VISIBLE', 
  data: null,
}

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:

<div id="add-event-listener-to-this-element">
  <document-reader></document-reader>
</div>
"Camera" button is pressed.

document-reader, camera-snapshot

{
  action: 'PRESS_CAMERA_BUTTON', 
  data: null,
}
"Files" button is pressed.

document-reader, camera-snapshot

{
  action: 'PRESS_FILE_BUTTON', 
  data: null,
}
"Retry" button is pressed.

document-reader, camera-snapshot

{
  action: 'PRESS_RETRY_BUTTON', 
  data: null,
}
"Skip page" button is pressed.

document-reader

{
  action: 'PRESS_SKIP_BUTTON', 
  data: null,
}

This event available only in document-reader.

"Capture" button is pressed.

document-reader, camera-snapshot

{
  action: 'PRESS_CAPTURE_BUTTON', 
  data: null,
}
"Change camera" button is pressed.

document-reader, camera-snapshot

{
  action: 'PRESS_CHANGE_CAMERA_BUTTON', 
  data: null,
}
"Mobile device" button is pressed.

document-reader

{
  action: 'PRESS_REMOTE_DEVICE_BUTTON', 
  data: null,
}
"Mirroring" button is pressed.

document-reader, camera-snapshot

{
  action: 'PRESS_MIRRORING_BUTTON', 
  data: null,
}
The document contains another page.

document-reader

{
  action: 'NEW_PAGE_AVAILABLE', 
  data: null,
}

This event available only in document-reader.

Recognition of a new page has started.

document-reader

{
  action: 'NEW_PAGE_STARTED', 
  data: null,
}

This event available only in document-reader.

"Close" button is pressed.

document-reader, camera-snapshot

{
  action: 'CLOSE', 
  data: null,
}
"Close" button is pressed on the document recognition screen.

document-reader, camera-snapshot

{
  action: 'CAMERA_PROCESS_CLOSED', 
  data: null,
}
Recognition from the camera has started.

document-reader, camera-snapshot

{
  action: 'CAMERA_PROCESS_STARTED', 
  data: null,
}
Video stream has started.

document-reader, camera-snapshot

{
  action: 'VIDEO_STARTED', 
  data: null,
}
Video stream has stopped.

document-reader, camera-snapshot

{
  action: 'VIDEO_STOPPED', 
  data: null,
}
File processing has started.

document-reader, camera-snapshot

{
  action: 'FILE_PROCESS_STARTED', 
  data: null,
}
The work of the component is completed successfully.

document-reader, camera-snapshot

{
  action: 'PROCESS_FINISHED', 
  data: {
    response: { ... },
    status: 1
  }
}
The work of the component is completed by timeout.

document-reader

{
  action: 'PROCESS_FINISHED', 
  data: {
    response: { ... },
    status: 2
  }
}

This event available only in document-reader.

The work of the component failed.

document-reader, camera-snapshot

{
  action: 'PROCESS_FINISHED', 
  data: {
    reason: 'CAMERA_PERMISSION_DENIED',
    status: 0
  }
}
Component is initialized and ready to work.

document-reader

{
  action: 'SERVICE_INITIALIZED',
  data: null,
}

This event available only in document-reader.

The transaction has been successfully uploaded from the delegated device.

document-reader

{
  action: 'REMOTE_TRANSACTION_UPLOADED',
  data: {
    id: 'df4e210a-8411-411b-998e-a7c7f6b4a770',
    state: 1,
    updatedAt: '2024-09-19T11:05:21.473286Z'       
  },
}

This event available only in document-reader.

Remote processing has been completed successfully.

document-reader

{
  action: 'REMOTE_PROCESS_FINISHED',
  data: {
    response: { ... },
    status: 1       
  },
}

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 nameAttribute nameDescriptionData typeDefault valueValuesAvailable in
localelocaleThe 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.stringenru, 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, nodocument-reader, camera-snapshot
internalScenariointernal-scenarioThe component document verification scenario.stringMrzAndLocateMrzAndLocate, MrzOrLocate, Mrz, Locate, Barcode, MrzOrBarcode, BarcodeAndLocatedocument-reader
multipageProcessingmultipage-processingWhether 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.booleanfalsetrue, falsedocument-reader
startScreenstart-screenWhether 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.booleanfalsetrue, falsedocument-reader, camera-snapshot
multipleFileInputmultipleWhether to allow uploading more than one file via the file system. Can be set to true only if startScreen is true.booleantruetrue, falsedocument-reader, camera-snapshot
cameraIdcamera-idAbility to select a camera. You can get the device ID using navigator.mediaDevices.enumerateDevices().stringundefinedcamera id string valuedocument-reader, camera-snapshot
devLicenselicenseTo use the component on test environments, set the base64 license value to the license attribute.stringundefinedbase64 license valuedocument-reader
regulaLogocopyrightShow Regula copyright footer.booleantruetrue, falsedocument-reader, camera-snapshot
changeCameraButtonchange-cameraShow the camera switch button.booleanfalsetrue, falsedocument-reader, camera-snapshot
closeButtonclose-buttonShow the close button.booleantruetrue, falsedocument-reader, camera-snapshot
captureButtoncapture-buttonShow the capture button.booleantruetrue, falsedocument-reader
skipButtonShow the skip button for the second page.booleantruetrue, falsedocument-reader
captureModeSets 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.stringautoauto, captureVideo, captureFramedocument-reader
resolutionSets the resolution of the video stream from the camera.object{ width: 1920, height: 1080 }{ width: number, height: number }document-reader, camera-snapshot
cameraModeSelects the front or rear camera of the device.objectenvironmentenvironment, userdocument-reader, camera-snapshot
flipFrontIconSets 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.stringundefinedlink to image, base64 string, imported imagedocument-reader
flipBackIconSets 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.stringundefinedlink to image, base64 string, imported imagedocument-reader
cameraFrameBorderWidthSets the thickness of the document capture frame.number5any numberdocument-reader
backgroundMaskAlphaSets the transparency of the background outside the frame.number0.5from 0 to 1document-reader
cameraFrameLandscapeAspectRatioSets the aspect ratio of the capture frame for landscape mode.numberdepends on the scenarioany numberdocument-reader
cameraFramePortraitAspectRatioSets the aspect ratio of the capture frame for portrait mode.numberdepends on the scenarioany numberdocument-reader
statusIconShow status icon.booleantruetrue, falsedocument-reader
statusPositionMultiplierSets the vertical position of the status message.numberundefinedfrom 0 to 2document-reader
cameraFrameOffsetWidthSets the offset of the capture frame.numberundefinedany numberdocument-reader
cameraFrameVerticalPositionMultiplierSets the offset of the capture frame from the top edge.numberundefinedfrom 0 to 2document-reader
cameraFrameShapeTypeSets the capture frame shape type.stringlineline, cornersdocument-reader
cameraFrameLineCapSets the style of the end of the capture frame line when cameraFrameShapeType='corners'stringbuttbutt, round, squaredocument-reader
cameraFrameLineLengthSets the length of the capture frame line when cameraFrameShapeType='corners'number5any numberdocument-reader
cameraFrameCornerRadiusSets the radius of rounding of the capture frame.number15any numberdocument-reader
cameraFrameDefaultColorSets the color of the capture frame.stringrgba(255, 255, 255, 0.9)any color stringdocument-reader
cameraFrameActiveColorSets the capture frame color when a document is detected.stringrgba(30, 130, 76, 0.9)any color stringdocument-reader
statusTextColorSets the color of the text message status.stringwhiteany color stringdocument-reader, camera-snapshot
statusBackgroundColorSets the background color of the message status.stringrgba(27, 16, 31, 0.5)any color stringdocument-reader, camera-snapshot
cameraFrameShow the capture frame.booleantruetrue, falsedocument-reader
captureButtonDelayShow the capture button after delay.numberundefinedany numberdocument-reader
nonceSets the unique nonce value to maintain the CSP policy.stringundefinedunique nonce valuedocument-reader, camera-snapshot
videoRecordSets 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 objectundefinedtrue, false, { delay: number, duration: number, bitrate: number }document-reader
videoCaptureMotionControlEnables device shaking control.booleanfalsetrue, falsedocument-reader
fromCameraButtonShow the camera button.booleantruetrue, falsedocument-reader, camera-snapshot
uploadFileButtonShow the files button.booleantruetrue, falsedocument-reader, camera-snapshot
mirrorButtonShow the mirroring button.booleanfalsetrue, falsedocument-reader, camera-snapshot
mirrorTypeSets the initial value of video mirroring.stringmirror - for front camera, noMirror - for back camera,mirror, noMirrordocument-reader, camera-snapshot
mobileDelegateChanges the success screen in case of delegating scanning via a mobile device.booleanfalsetrue, falsedocument-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: {
    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);

Delegating scan to device with better camera

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).

1. "From other phone" action may be configured on the start screen:
  • add 'delegateProcessing' and 'tag':
    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
    }
    
  • these settings will unlock "From other phone" option that shows the user QR Code with url (i.e. https://your-page.com?tag=123)
  • the component will emit REMOTE_TRANSACTION_UPLOADED event with the most recent transaction uploaded with your session tag. Transaction id may be used to trigger full process backend reprocessing (i.e use Document Reader Webclient)
  • the component will emit REMOTE_PROCESS_FINISHED event with a result of the most recent processed transaction. It is similar to PROCESS_FINISHED event but may contain more data due to backend reprocessing
2. Configure Delegate page component on delegateURL:
  • configure backend reprocessing
  • backendProcessing setting for the device and delegateProcessing setting for the main page must match
  • set transaction tag
    processor.recognizerProcessParam = {
     tag: new URL(window.location.href).searchParams.get('tag') // assume session Id tag was added to URL params
    }
    
  • use the same tag as on the main page
    element.settings = {
     startScreen: false, // From camera recognition is expected
     mobileDelegate: true
    }
    
  • use finalizePackage() to send the data for further reprocessing

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.

VariableInfoDefault value
--font-familyThe 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-sizeThe font size for the text elements.16px
--main-colorColor for the graphic elements of the component. By default, the brand Regula violet is set.#7E57C5
--hover-colorButtons hover color.#c994ff
--active-colorButtons 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>
Inserting component in Flex and Grid layouts

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
}
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.

LabelDefault message in en localeUsed in
doneDone!document-reader, camera-snapshot
fileCorruptThis file is corrupt or not supporteddocument-reader, camera-snapshot
somethingWentWrongSomething went wrongdocument-reader, camera-snapshot
tryAgainTry againdocument-reader, camera-snapshot
cameraUnavailableCamera unavailable!document-reader, camera-snapshot
preparingCameraPreparing the camera...document-reader, camera-snapshot
noCameraAvailableNo camera availabledocument-reader, camera-snapshot
incorrectCameraIdNo camera with the specified ID found.document-reader, camera-snapshot
galleryGallerydocument-reader, camera-snapshot
filesFilesdocument-reader, camera-snapshot
cameraCameradocument-reader, camera-snapshot
largeFileThis file is too large to be uploadeddocument-reader
versionNotSupportedYour browser version is not supporteddocument-reader
httpNotSupportedHTTPS is not useddocument-reader
insecurePageContextInsecure page contextdocument-reader
timeoutTimeoutdocument-reader
preparingServicePreparing the service...document-reader
placeDocumentIntoFrameFit the document into the framedocument-reader
noFocusNo camera focusdocument-reader
moveCloserMove closerdocument-reader
glaresOnDocumentAvoid glare on the documentdocument-reader
holdDocumentStraightHold the document straightdocument-reader
documentProcessingDocument processing...document-reader
flipDocumentFlip the documentdocument-reader
keepDeviceStillHold the device stilldocument-reader
positionDocumentCenterPosition the document in the centercamera-snapshot
uploadPhotoUpload a photocamera-snapshot
switchToMobileSwitch to mobiledocument-reader
openPhoneCameraOpen the camera on your mobile device, scan the QR code, and follow the linkdocument-reader
pleaseWaitPlease wait...document-reader
mobileDeviceMobile devicedocument-reader
verifyYourIdentityVerify your identity documentdocument-reader
fromCameraFilesMobileDesktopCapture a document using the computer’s camera, or upload it from files, or scan it on a mobile devicedocument-reader
fromCameraGalleryMobileCapture a document using the computer’s camera, or upload it from gallerydocument-reader
badLicenseThe license cannot be found or has expireddocument-reader
fromCameraFilesDesktopCapture a document using the computer’s camera, or upload it from filesdocument-reader
fromCameraMobileDesktopCapture a document using the computer’s camera, or scan it on a mobile devicedocument-reader
fromFilesMobileDesktopUpload a document from files, or scan it on a mobile devicedocument-reader
fromCameraDesktopUse the computer's camera to capture a documentdocument-reader
fromFilesDesktopPick a document from the files and upload itdocument-reader
fromMobileDesktopUse your mobile camera to capture a documentdocument-reader
fromGalleryMobilePick a document from the gallery and upload itdocument-reader
returnToComputerReturn to the computerdocument-reader
documentCapturedYour document has been captureddocument-reader

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 result
  • currentPage.startNextPage method for starting the next page procession
  • currentPage.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 from navigator.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. 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
  }
}

FAQs

Package last updated on 04 Nov 2024

Did you know?

Socket

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.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc