Angular Integration
Learn how to integrate the fw-ocrid
library in your Angular project by creating a reusable component for OCR functionality, step by step.
Basic Implementation
import { Component, ViewChild, OnInit, OnDestroy } from '@angular/core';
import { OcrId, Envs, EventType, EventTypeUserFeedback, Endpoints, ResultHelper } from 'fw-ocrid';
@Component({
selector: 'app',
template: `<div class="videoContainer" #container></div>`
})
export class App implements OnInit, OnDestroy {
@ViewChild('videoContainer', { static: false }) videoContainer: any; // Video container reference
private ocrid: OcrId; // OCRID instance
public processId: string;
public result: any;
async ngOnInit(): Promise<void> {
// Initialize OCRID with API Key, environment, optional config, and optional language
this.ocrid = new OcrId('YOUR_API_KEY', Envs.PRE3, undefined, 'en');
// Subscribe to user feedback events
this.ocrid.events(EventType.USER_FEEDBACK).subscribe((feedback) => {
switch (feedback) {
case EventTypeUserFeedback.SHOW_DOCUMENT_FRONT_SIDE:
console.log('Show the front side of the document.');
break;
case EventTypeUserFeedback.SHOW_DOCUMENT_REVERSE_SIDE:
console.log('Show the reverse side of the document.');
break;
case EventTypeUserFeedback.DOCUMENT_FRONT_SIDE_COMPLETED:
console.log('Front side scanned successfully.');
break;
case EventTypeUserFeedback.PROCESS_FAILED_DUE_ANALYSIS_ERROR:
console.error('Process failed due to an analysis error.');
break;
case EventTypeUserFeedback.PROCESS_FINISHED:
console.log('Scanning process completed.');
break;
}
});
// Subscribe to result events
this.ocrid.events(EventType.RESULT).subscribe((result) => {
console.log('Scan completed successfully:', result);
// Get result using processId
this.getOcrResult(this.processId);
this.ocrid.close(); // Close the OCRID instance
});
// Subscribe to error events
this.ocrid.events(EventType.ERROR).subscribe((error) => {
console.error('An error occurred during scanning:', error);
});
// Start the scanning process
this.processId = await this.ocrid.startStream(this.videoContainer.nativeElement);
console.log('OCR process started.');
}
async getOcrResult(processId: string): Promise<void> {
try {
// Method 1: Using ResultHelper (recommended)
this.result = await ResultHelper.get(processId, Envs.PRE3);
console.log('Result obtained:', this.result);
// Access specific result fields
if (this.result?.success) {
const documentTypes = this.result.value.types;
const fields = this.result.value.fields;
const images = this.result.value.images;
console.log('Document type:', documentTypes);
console.log('Extracted fields:', fields);
console.log('Images:', images);
}
// Method 2: Using direct HTTP call to endpoint
// const url = `${Endpoints[Envs.PRE3]}result/${processId}`;
// Use Angular's HttpClient for the call
// this.http.get(url).subscribe(data => {
// console.log('Result from API:', data);
// });
} catch (error) {
console.error('Error getting OCR result:', error);
}
}
ngOnDestroy(): void {
// Release resources and close OCRID
if (this.ocrid) {
this.ocrid.close();
}
}
}
Result Retrieval and Processing
Once the scanning process is completed, you will obtain a processId
that allows you to retrieve the OCR analysis results. There are two main ways to obtain these results:
Method 1: Using ResultHelper (Recommended)
The library provides a ResultHelper
class that simplifies result retrieval:
import { ResultHelper, Envs } from 'fw-ocrid';
async getOcrResult(processId: string): Promise<void> {
try {
// Get result using the helper provided by the library
const result = await ResultHelper.get(processId, Envs.PRE3);
console.log('Result obtained:', result);
// Process data as needed
if (result?.success) {
// Identified document types
const documentTypes = result.value.types;
// Extracted document fields
const fields = result.value.fields;
// Captured images
const images = result.value.images;
// Validations performed
const validations = result.value.validations;
}
} catch (error) {
console.error('Error getting result:', error);
}
}
Method 2: Direct HTTP Call
Alternatively, you can make a direct HTTP call to the corresponding endpoint:
import { HttpClient } from '@angular/common/http';
import { Endpoints, Envs } from 'fw-ocrid';
constructor(private http: HttpClient) {}
getOcrResultManual(processId: string): void {
// Build URL using predefined Endpoints
const url = `${Endpoints[Envs.PRE3]}result/${processId}`;
// Make GET request
this.http.get<IResult>(url).subscribe({
next: (result) => {
console.log('Result obtained:', result);
// Process result as needed
},
error: (error) => {
console.error('Error getting result:', error);
}
});
}
Result Structure
The obtained result has the following structure:
interface IResult {
id: string; // Process ID
startTimestamp: number; // Start timestamp
endTimestamp: number; // End timestamp
success?: boolean; // Success indicator
value?: {
types: Array<{ // Identified document types
name: string; // Document type name
year: number; // Document year
id: string; // Document type ID
probability: number; // Match probability
country: string; // Document country
}>;
fields: Array<{ // Extracted document fields
name: string; // Field name
value: any; // Extracted value
}>;
authenticity: Array<{ // Authenticity validations
name: string;
value: any;
}>;
images: Array<{ // Captured images
name: string;
value: any; // Usually base64 value
}>;
validations: Array<{ // Additional validations
name: string;
value: any;
}>;
};
}
Key Implementation Points
-
Component Initialization: An instance of
OcrId
is created by providing the required parameters such as the API key, execution environment (Envs.PRE3
) and language ('en'
). -
Event Subscription: The component subscribes to three main types of events:
- User Feedback Events (
USER_FEEDBACK
): Indicates actions that the user should perform, such as showing the front or back of the document. - Result Events (
RESULT
): Signals the success of the scanning process, delivering the obtained data. - Error Events (
ERROR
): Captures and handles errors that occur during the process.
- User Feedback Events (
-
Camera Management:
- The
startStream
method is used to start the camera stream and capture document data. - The video container (
videoContainer
) is configured to display the camera stream in real-time.
- The
-
Result Retrieval:
- Once scanning is complete, the
processId
is used to obtain the OCR analysis results. - You can use
ResultHelper.get()
or make a direct call to the/result/{processId}
endpoint. - The results include detailed information about the scanned document, including type, extracted fields, and images.
- Once scanning is complete, the
-
Process Finalization: Once the OCR process is completed, the
OcrId
instance is closed using theclose
method to release the resources used. -
Resource Cleanup: In the
ngOnDestroy
method, it ensures that all resources related to the OCR process are properly released when the component is destroyed. -
Result and Error Handling:
- Scanning results are processed as needed for display or storage.
- Errors are handled and logged to provide diagnostic information in case of failures.
-
License Management:
- Initially, request access from Finwave for the URLs where you plan to use the component, specifying the following:
- Which URLs are for production.
- Which URLs are for testing or development.
- Once you receive the license, you will be able to use the product correctly.
- For local testing, a temporary license will be provided. You can work in three types of environments: production (PRO3), testing (PRE3), and development (DEV3).
- To use the temporary license, add the following code in the browser before using the component:
window.regulaLicense = { license: "..." };
- Initially, request access from Finwave for the URLs where you plan to use the component, specifying the following:
-
Angular Demo
To test the functionality of the OCR ID program, a demo has been implemented in Angular that provides an interactive interface. This allows users to explore the features and behavior of the library without the need to integrate it into their own interface.
- You can access the demo at the following link: Angular-Demo.