Skip to content

Document Reader SDK Web Components


Overview

The Document Reader web components let you add document verification to your web site. The components can capture a document from the device camera or process an uploaded image, crop the image by the document boundaries, detect the presence or absence of the machine readable zone (MRZ) and return the MRZ text fields.

The Document Reader web components package contains:

  • UI web components for document recognition.
  • the document reader SDK for creating your custom document reader UI interface.

The UI web components are:

  • document-reader for documents recognition.
  • camera-snapshot for capturing images from a camera or uploading from a gallery.

This package contains UI web components and SDK for documents recognition.

Before you start

Please note that:

  • The components work only under the HTTPS protocol on the website.
  • The components library does register the components on the web page itself, so make sure to import the library to your website before adding the components to the web page code.
  • The UI components and the SDK use the getUserMedia method to display the video stream from the camera. This feature is available only in secure contexts (HTTPS).
  • We do not include polyfills for older browsers in the package. If you need to support older browser versions in your project, you can easily install the required package. For example, you can find the necessary polyfills at https://www.npmjs.com/package/@webcomponents/webcomponentsjs.

Compatibility

Devices Chrome FireFox Safari
Mobile (iOS) 99 99 11
Mobile (Android) 66 61 -
Desktop 61 60 11

UI components

Integration via NPM

Install @regulaforensics/vp-frontend-document-components:

npm i @regulaforensics/vp-frontend-document-components

Import defineComponents and DocumentReaderService from @regulaforensics/vp-frontend-document-components into your .js file:

// If you use module bundler
import { defineComponents, DocumentReaderService } from '@regulaforensics/vp-frontend-document-components';

// If you don't use module bundler
import { defineComponents, DocumentReaderService } from './node_modules/@regulaforensics/vp-frontend-document-components/esm/main.js';

Add DocumentReaderService to the global variable RegulaDocumentSDK, define the components and initialize the service:

window.RegulaDocumentSDK = new DocumentReaderService();

defineComponents().then(() => window.RegulaDocumentSDK.initialize());
// defineComponents().then(() => window.RegulaDocumentSDK.initialize({ license: 'BASE64_LICENSE_KEY' })); // To use the document-reader component on test environments, you have to set the base64 license

// Notice: If you use only the camera-snapshot component, then it is not necessary to create a global variable and prepare the service, use only defineComponents();

Add the component name to the .html file. The available components are:

<document-reader></document-reader> <!-- for documents recognition -->
<camera-snapshot></camera-snapshot> <!-- to capture images from the camera and gallery -->

Integration via CDN

Connect the script in your .html file. Here is the CDN link: unpkg.com/:package@:version/:file

For example:

<script src="https://unpkg.com/@regulaforensics/vp-frontend-document-components@latest/dist/main.js"></script>

In your .js file define the components and prepare the service. DocumentReaderService and defineComponents are available in the global variable window.Regula:

const { defineComponents, DocumentReaderService } = window.Regula;

window.RegulaDocumentSDK = new DocumentReaderService();

defineComponents().then(() => window.RegulaDocumentSDK.initialize());
// defineComponents().then(() => window.RegulaDocumentSDK.initialize({ license: 'BASE64_LICENSE_KEY' })); // To use the document-reader component on test environments, you have to set the base64 license

// Notice: If you use only the camera-snapshot component, then it is not necessary to create a global variable and prepare the service, use only defineComponents();

Add the component name to the .html file. The available components are:

<document-reader></document-reader> <!-- for documents recognition -->
<camera-snapshot></camera-snapshot> <!-- to capture images from the camera and gallery -->

Document recognition parameters

After adding DocumentReaderService to the global variable, you can change the default document recognition settings:

// Default settings for video capture (From camera button):
window.RegulaDocumentSDK.recognizerProcessParam = {
  processParam: {
    returnUncroppedImage: true,
    scenario: 'MrzAndLocate',
    multipageProcessing: false,
    returnPackageForReprocess: false,
    timeout: 20000,
    resultTypeOutput: [],
    imageQa: {
      expectedPass: ['dpiThreshold', 'glaresCheck', 'focusCheck'],
      dpiThreshold: 130,
      glaresCheck: true,
      glaresCheckParams: {
        imgMarginPart: 0.05,
        maxGlaringPart: 0.01,
      },
    },
  },
};

// Default settings for image processing (From gallery button):
window.RegulaDocumentSDK.imageProcessParam = {
  processParam: {
    scenario: 'MrzAndLocate',
    returnUncroppedImage: true,
    returnPackageForReprocess: false,
  },
};

You can also set the session id:

window.RegulaDocumentSDK.imageProcessParam = {
  tag: 'your session id',
};

Descriptions of settings

Setting Info Data type Default value Values
returnUncroppedImage Whether to return input images in output. boolean true true, false
scenario The recognition scenario. string 'MrzAndLocate' 'MrzAndLocate', 'MrzOrLocate', 'Mrz', 'Locate'
multipageProcessing Whether to enable multi-page document processing mode. boolean true true, false
timeout Recognition timeout in milliseconds. After this time process will be finished. number 2000 numbers > 0
resultTypeOutput Types of results to return in response. [] - all available types. number[] [] 1 - DocumentImageResult, 3 - TextDataResult, 5 - DocBarCodeInfo, 6 - GraphicsResult, 8 - DocumentTypesCandidatesResult, 9 - ChosenDocumentTypeResult, 20 - AuthenticityResult, 15 - LexicalAnalysisResult, 17 - TextDataResult, 18 - TextDataResult, 19 - GraphicsResult, 30 - ImageQualityResult, 33 - StatusResult, 36 - TextResult, 37 - ImagesResult, 85 - DocumentPositionResult, 102 - TextDataResult, 103 - GraphicsResult, 50 - LicenseResult, 49 - EncryptedRCLResult
returnPackageForReprocess Whether to return the package for reprocessing on the backend. boolean false true, false
imageQa When enabled, the image quality check status affects the 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 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 field will be divided into ft_First_Name, ft_Second_Name, ft_Third_Name, ft_Fourth_Name, ft_Last_Name fields. boolean false true, false

Attention! If the multipage-processing or internal-scenario attributes are set, the multipageProcessing and scenario settings will be ignored.

Events

You can subscribe to the component events.

For example:

const documentReaderComponent = document.querySelector('document-reader'); 
const cameraSnapshotComponent = document.querySelector('camera-snapshot');

documentReaderComponent.addEventListener('document-reader', (event) => console.log(event.detail)); // Event listener for document-reader component.
cameraSnapshotComponent.addEventListener('camera-snapshot', (event) => console.log(event.detail)); // Event listener for camera-snapshot component.

The document-reader type of event is generated for the document-reader component, and camera-snapshot type of event is generated for the camera-snapshot component.

The generated event object (event.detail) contains two fields that describe the event:

{
  action: 'PRESS_CAMERA_BUTTON', // The type of action that generated the event (all actions are described in the table below)
  data: null, // Component data
}

Type of actions:

Type of action Description of the action In which component is present
ELEMENT_VISIBLE Component is appended in the DOM. document-reader, camera-snapshot
PRESS_CAMERA_BUTTON The "From camera" button is pressed. document-reader, camera-snapshot
PRESS_FILE_BUTTON The "From gallery" button is pressed. document-reader, camera-snapshot
PRESS_RETRY_BUTTON The "Retry" button is pressed. document-reader, camera-snapshot
PRESS_SKIP_BUTTON The "Skip" button is pressed. document-reader
PRESS_CAPTURE_BUTTON The "Capture" button is pressed. document-reader, camera-snapshot
PRESS_CHANGE_CAMERA_BUTTON The "Change camera" button is pressed. document-reader, camera-snapshot
PRESS_MIRRORING_BUTTON The "Mirroring" button is pressed. document-reader, camera-snapshot
NEW_PAGE_AVAILABLE The document contains another page. document-reader
NEW_PAGE_STARTED Recognition of a new page has started. document-reader
CLOSE The "Close" button is pressed. document-reader, camera-snapshot
CAMERA_PROCESS_CLOSED The "Close" button is pressed on the document recognition screen. document-reader, camera-snapshot
CAMERA_PROCESS_STARTED Recognition from the camera has started. document-reader
VIDEO_STARTED Video stream started. document-reader, camera-snapshot
VIDEO_STOPPED Video stream stopped. document-reader, camera-snapshot
FILE_PROCESS_STARTED File processing has started. document-reader, camera-snapshot
PROCESS_FINISHED The component has finished its work. document-reader, camera-snapshot
SERVICE_INITIALIZED The component has started its work. document-reader

In cases of successful operation of the components, the data field will contain the following fields:

{
  response: { ... }, // component result
  status: 1 // Or 2, if the process is completed by timeout
}

In cases of unsuccessful work, the data field will contain the following fields:

{
  reason: 'CAMERA_PERMISSION_DENIED', // error reason (possible causes of errors are described in the table below)
  status: 0
}

Description of statuses:

Status Description of the status
0 Process failed.
1 Process is completed successfully.
2 Process is completed by timeout.

Table of error causes:

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.
UNKNOWN_ERROR Unknown error.
NOT_SUPPORTED The browser is not supported.
CAMERA_UNKNOWN_ERROR Unknown camera error.
CAMERA_PERMISSION_DENIED Access to the camera is prohibited.
NO_CAMERA There is no camera.
CONNECTION_ERROR Connection errors.

The table below describes the cases of event generation:

Event condition Event type Event object `event.detail` Description
The 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>
The "From camera" button is pressed. `document-reader`, `camera-snapshot`
{
  action: 'PRESS_CAMERA_BUTTON', 
  data: null,
}
The "From gallery" button is pressed. `document-reader`, `camera-snapshot`
{
  action: 'PRESS_FILE_BUTTON', 
  data: null,
}
The "Retry" button is pressed. `document-reader`, `camera-snapshot`
{
  action: 'PRESS_RETRY_BUTTON', 
  data: null,
}
The "Skip page" button is pressed. `document-reader`
{
  action: 'PRESS_SKIP_BUTTON', 
  data: null,
}
This event available only in `document-reader`.
The "Capture" button is pressed. `document-reader`, `camera-snapshot`
{
  action: 'PRESS_CAPTURE_BUTTON', 
  data: null,
}
The "Change camera" button is pressed. `document-reader`, `camera-snapshot`
{
  action: 'PRESS_CHANGE_CAMERA_BUTTON', 
  data: null,
}
The "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`.
The "Close" button is pressed. `document-reader`, `camera-snapshot`
{
  action: 'CLOSE', 
  data: null,
}
The "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 started. `document-reader`, `camera-snapshot`
{
  action: 'VIDEO_STARTED', 
  data: null,
}
Video stream 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`.

Response

You can get the response of the component 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 each frame, you can set the callback function:

window.RegulaDocumentSDK.recognizeListener = (response) => console.log(response);

Settings and attributes

There are two ways to set the settings, using the settings property or using attributes.

Using settings property:

const element = document.createElement('document-reader');

element.settings = {
  startScreen: true,
  internalScenario: 'Locate',
  multipageProcessing: true,
};

Using attributes:

<document-reader start-screen internal-scenario="Locate"></document-reader>

We recommend using the settings property. New settings in the future will be available only in this method.

Setting name Attribute name Info 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
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 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 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 from 0 to 2 document-reader
cameraFrameOffsetWidth Sets the offset of the capture frame from the side edges in portrait mode. number any number document-reader
cameraFrameVerticalPositionMultiplier Sets the offset of the capture frame from the top edge in portrait mode. number 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
cameraFrame Show the capture frame. boolean true true, false document-reader
nonce Sets the unique nonce value to maintain the CSP policy. string undefined unique nonce value document-reader, camera-snapshot

Customization

Font and colors

Using CSS variables, you can change the font and the main colors of the components.

Variable Info Default value
--font-family The font family of all text elements. If you change the font family, make sure to adjust the fond size so the message on the start screen would fit the frame. Noto Sans, sans-serif
--font-size The font size for the text elements. 16px
--main-color Color for the graphic elements of the component. By default, the brand Regula violet is set. #bd7dff
--hover-color Buttons hover color. #c994ff
--active-color Buttons active color. #bd7dff

For example:

CSS:

.my-custom-style {
    --font-family: Arial, sans-serif;
    --main-color: green;
}

HTML:

<document-reader class="my-custom-style"></document-reader>

Messages

To change the standard component messages or any text, specify the language you are using (or add your own) and the label you want to change (you can see the list of available languages in the attribute descriptions section, locale attribute):

const element = document.createElement('document-reader');

element.translations = {
   en: {
      fromCamera: 'Use your camera',
   },
};

body.append(element);

Note: to see the changes, don't forget to set the language you changed to the locale attribute.

<document-reader locale="en"></document-reader>

List of labels used in the component:

Label Default message in en locale Used in
success Success! document-reader, camera-snapshot
fileCorrupt This file is corrupt or not supported document-reader, camera-snapshot
selectAnotherFile Please select another file document-reader, camera-snapshot
error Error! document-reader, camera-snapshot
somethingWentWrong Something went wrong document-reader, camera-snapshot
tryAgain Try again document-reader, camera-snapshot
fromCamera From camera document-reader, camera-snapshot
fromGallery From gallery document-reader, camera-snapshot
cameraUnavailable Camera unavailable! document-reader, camera-snapshot
preparingCamera Preparing the camera... document-reader, camera-snapshot
noCameraAvailable No camera available document-reader, camera-snapshot
incorrectCameraId No camera with the specified ID found. document-reader, camera-snapshot
allowAccessToCamera Allow access to the camera and reload this page to continue. document-reader, camera-snapshot
cameraConnection Make sure the camera is connected correctly. document-reader, camera-snapshot
checkCameraId Check if the specified camera ID is correct. document-reader, camera-snapshot
scanIDInBrowser Scan an ID in your browser document-reader
useYourDeviceCamera Use your device camera to scan a document or select a photo of the document from the gallery document-reader
processingFinished Processing finished. document-reader
largeFile This file is too large to be uploaded document-reader
selectSmallerFile Please select a smaller file document-reader
versionNotSupported Your browser version is not supported document-reader
updateBrowser Update your browser version document-reader
licenseError A license error has occurred document-reader
licenseExpired The license cannot be found or has expired document-reader
timeout Timeout document-reader
processing Processing... document-reader
preparingService Preparing the service... document-reader
detectingDocument Detecting a document... document-reader
placeDocumentIntoFrame Fit the document into the frame document-reader
noFocus No camera focus document-reader
moveCloser Move closer document-reader
glaresOnDocument Avoid glare on the document document-reader
holdDocumentStraight Hold the document straight document-reader
documentProcessing Document processing... document-reader
flipDocument Flip the document document-reader
verified Verified! document-reader
positionDocumentCenter Position the document in the center camera-snapshot
photoCapturedSuccessfully The photo is captured successfully. camera-snapshot
uploadPhoto Upload a photo camera-snapshot
useCameraOrGallery Use your device camera or select a photo from the gallery camera-snapshot

Document reader SDK

You can use the document-reader SDK to create your own UI interface.

SDK integration via NPM

Install @regulaforensics/vp-frontend-document-components:

npm i @regulaforensics/vp-frontend-document-components

Import DocumentReaderProcessor from @regulaforensics/vp-frontend-document-components into your .js file:

import { DocumentReaderProcessor } from '@regulaforensics/vp-frontend-document-components'; // If you use module bundler. In other cases use full path '/node_modules/@regulaforensics/vp-frontend-document-components/esm/main.js'.

Add video tag to .html file then prepare and initialize DocumentReaderProcessor:

const videoElement = document.getElementById('yourVideoElement');
const processor = new DocumentReaderProcessor(videoElement);

try {
   await processor.initialize({ license: 'BASE64_LICENSE_KEY' }); // Set license object ONLY on test environments. In the production build call initialize(); without a license object.

   const result = await processor.startRecognition();  // Result of the document recognition will be located here.

   processor.stopRecognition();

   console.log(result);
} catch (e) {
   console.log(e);
}

SDK integration via CDN

Connect the script in your .html file. CDN link: unpkg.com/:package@:version/:file

For example:

<!-- Replace <VERSION> with the package version. The list of versions is available on NPM in the versions section -->
<script src="https://unpkg.com/@regulaforensics/vp-frontend-document-components@latest/dist/main.js"></script>

Add video tag to .html file then prepare and initialize DocumentReaderProcessor. DocumentReaderProcessor is available in the global variable window.Regula:

const { DocumentReaderProcessor } = window.Regula;

const videoElement = document.getElementById('yourVideoElement');
const processor = new DocumentReaderProcessor(videoElement);

try {
   await processor.initialize({ license: 'BASE64_LICENSE_KEY' }); // Set license object ONLY on test environments. In the production build call initialize(); without a license object.

   const result = await processor.startRecognition(); // Result of the document recognition will be located here.

   processor.stopRecognition();

   console.log(result);
} catch (e) {
   console.log(e);
}

Available DocumentReaderProcessor methods

initialize

Initializes the processor. Accepts an object with a base64 license. An object with a license must be installed only to work on test environments. Do not install an object with a license in production mode:

await processor.initialize({ license: 'BASE64_LICENSE_KEY' });

startRecognition

The method starts the video stream and starts the process of recognizing the document. Returns the result of document processing:

const result = await processor.startRecognition();

To process multi-page documents, add the callback function to the method. The callback function takes in an object with an intermediate result of processing, a method for starting the next page and a method for completing the process:

/**
 * @param {object} currentPage - Page data.
 * @param {object} currentPage.data - Page processing result.
 * @param {function} currentPage.startNextPage - The method of starting the recognition of the next page.
 * @param {function} currentPage.finishRecognition - Finish the process and return the result.
 */

async function pageListener(currentPage) {

    setTimeout(async () => {               
        await currentPage.startNextPage(); // Will start recognition of the next page in 3 seconds.
    }, 3000);                              // During this time, you can tell the user to turn the document over.
}

const result = await processor.startRecognition(pageListener);

processImage

Processes document files. Can process FileList or Blob array:

const file = 'FileList or Blob array';

const result = await processor.processImage(file);

switchCamera

If there are several cameras, it switches to the next one.

await processor.switchCamera();

stopRecognition

Stops the document recognition process and ends the video stream.

processor.stopRecognition();

DocumentReaderProcessor settings

You can change the default settings for video streaming and document recognition. The settings must be set before the document recognition process.

streamParam

Sets the video stream settings:

processor.streamParam = {
   cameraMode: 'environment',      // Camera facing mode. Can be 'environment' or 'user'. By default 'environment'.
   preferredCameraId: '',   // Selecting a camera by ID. The camera ID can be obtained using navigator.mediaDevices.enumerateDevices();. Not set by default.
   resolution: {            // Video resolution. By default 1280x720.
     width: 1280,
     height: 720, 
   },
}

recognizerProcessParam

Sets the settings for recognizing a document from the camera (startRecognition method):

// Default settings:
processor.recognizerProcessParam = {
   processParam: {
      scenario: 'MrzAndLocate',
      returnUncroppedImage: true,
      returnPackageForReprocess: false,
   },
};
See the list of all available settings here.

imageProcessParam

Sets the settings for recognizing a document as a file (processImage method):

// Default settings:
processor.imageProcessParam = {
   processParam: {
      scenario: 'MrzAndLocate',
      returnUncroppedImage: true,
      returnPackageForReprocess: false,
   },
}

See the list of all available settings here.

recognizeListener

Sets the callback function that takes in the processing result for each frame:

/**
 * @param {object} response - The result of processing each frame.
 */

function listener(response) {
  console.log(response);
}

processor.recognizeListener = listener; // Not set by default.

videoElement

Sets the video element to display the video stream from the camera. This setting will change the video element that you set when creating the instance new DocumentReaderProcessor(videoElement):

const videoElement = document.getElementById('HTMLVideoElement');

processor.videoElement = videoElement; // By default null.

isInitialized

Read-only property. Returns true if the processor has been initialized.

processor.isInitialized; // True or false.

isProcessing

Read-only property. Returns true if document recognition is not completed.

processor.isProcessing; // True or false.

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 our servers, but you can change the download source.

First, to download these files from our server, you can get the link in the window.RegulaDocumentSDK.workerPath field.

Then, in the ProcMgr.worker.js file, use the search to find: https://wasm.regulaforensics.com and replace the full link with your address. Upload all three files (ProcMgr.worker.js, ProcMgr.wasm, ProcMgr.data) to the location you specified. Also, change the address in windows.RegulaDocumentSDK:

For document reader UI component:

// Set the file upload address before initializing the service.
window.RegulaDocumentSDK.workerPath = 'https://my-wasm-and-worker-files.com';

For DocumentReaderProcessor:

const processor = new DocumentReaderProcessor(videoElement);

processor.workerPath = 'https://my-wasm-and-worker-files.com';

Note that the files must be located in the same directory and have the names specified above.

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 SDK web components are also available on Storybook.

FAQ

How do I collect logs?

Logging can be helpful when you run into any issues. They contain information on how you use our products that helps us analyze, troubleshoot, and debug any issues you may experience.

1. Add the log setting to the processParam:

{
  "processParam": {
    "log": true
  }
}

2. Open the Developer menu in your browser.

3. Go to the Console tab.

4. In Console, enter the following line:

localStorage.logger = 'main,wasm>console'

5. Reload the page.

6. Start processing. Logs will display in Console.