Development a UWP Report Scanning App

by | Sep 15, 2023 | Etcetera | 0 comments

Phrase: This text has been contributed by means of Eric Parker from Dynamsoft.

The Commonplace House home windows Platform (UWP) shall we in us to make bigger apps for rather a large number of House home windows units and distribute them throughout the House home windows Store. This is a stylish technology from Microsoft, used for building consumer apps. UWP apps can benefit from the most recent visual sorts and features available in the newest permutations of House home windows.

Dynamic Web TWAIN (DWT) is a JavaScript library used for document scanning. If you want to create a document scanning app for UWP, you’ll achieve this by means of the use of UWP’s WebView regulate.

The WebView regulate means that you can embed a data superhighway view within your UWP app, which is able to display data superhighway content material subject matter the use of the Microsoft Edge Legacy rendering engine.

This fashion leads to a hybrid app, combining each and every native UWP controls and a data superhighway cyber web web page to send the potential you need.

In this article, we can provide step-by-step instructions for growing your personal UWP document-scanning app.

Analysis of Construction a Document Scanning App in UWP

To make bigger a document scanning app in UWP, you’ll follow the ones steps:

  1. Get began by means of the use of the Commonplace House home windows App template to create a brand spanking new endeavor in your app.
  2. Next, copy the assets folder and demo data from the Dynamic Internet TWAIN library into your endeavor.
  3. Then, add a WebView regulate on your app’s UI and load the HTML doc.
  4. Customize your app’s conduct for eventualities where Dynamic Web TWAIN isn’t installed on the instrument.
  5. Benefit from the purposes of the House home windows Runtime API to improve your app’s capacity.

Must haves

The prerequisites for this endeavor are as follows:

  • Arrange of Visual Studio together with the House home windows 10 SDK.
  • The Dynamic Web TWAIN library.
See also  How to Configure WooCommerce Settings

Create a UWP Document Scanning App

Get began a New Commonplace House home windows App Endeavor

To start out out, open Visual Studio and create a brand spanking new endeavor for a Commonplace House home windows app.

Visual Studio New Project WindowVisual Studio New Project Window
Replica the Dynamic Web TWAIN Assets Folder and Demo to the Endeavor

To copy the Dynamic Web TWAIN (DWT) assets folder and demo, please follow the ones steps:

  1. Create a brand spanking new folder and establish it “DWT.”
  2. Click on on this hyperlink to acquire the HTML, CSS, and JavaScript data for the pre-built demo. Place the downloaded data into the “DWT” folder you created in Step 1.
  3. Replica the Assets folder from C:Program Information (x86)DynamsoftDynamic Web TWAIN SDK 18.3 to the DWT folder. Phrase that the fitting path may vary depending to your computer’s setup.
  4. Dynamic Web TWAIN Resources FolderDynamic Web TWAIN Resources Folder
Create a WebView Regulate and Load the HTML File
  1. Control the MainPage.xaml doc the use of the code supplied beneath:

     
 
  1. Upon launching the app, exchange the MainPage.xaml.cs doc to signify the WebView to the HTML doc.
public MainPage()
{
    this.InitializeComponent();
    WebView1.Navigate(new Uri("ms-appx-web:///DWT/index.html"));
}

If Dynamic Web TWAIN is installed, the document scanning serve as should be available throughout the WebView.

Document Scanning Feature in WebViewDocument Scanning Feature in WebView

If it isn’t installed, you might even see the following dialogue box:

Dialogue Box for Missing Dynamic Web TWAINDialogue Box for Missing Dynamic Web TWAIN

Phrase: To use the document scanning capacity, the JavaScript library of Dynamic Web TWAIN should be in contact with a space supplier. Shoppers should arrange this supplier quicker than the use of the scanning app.

Override the Default Behavior When Web TWAIN is Not Detected

If Web TWAIN isn’t detected, a download dialogue box will appear. However, downloading the installer throughout the WebView isn’t conceivable. To artwork spherical this, you’ll open the download link throughout the instrument’s native browser.

UWP’s WebView lets in data superhighway pages to send notifications to the app:

– Benefit from window.external.alert throughout the HTML match handler to send notifications by way of WebView.ScriptNotify.

Add the following C# code to allow the ideas superhighway cyber web web page to tell the app:

public MainPage()
{
    this.InitializeComponent();

    // Newly added
    List allowedUris = new List();
    allowedUris.Add(new Uri("ms-appx-web:///DWT/index.html"));

    WebView1.ScriptNotify += WebView1_ScriptNotify;  // Newly added
    WebView1.Navigate(new Uri("ms-appx-web:///DWT/index.html"));
}

// Newly added
private async void WebView1_ScriptNotify(object sender, NotifyEventArgs e)
{
    // Handles the message
}

First, in finding and open the dynamsoft.webtwain.arrange.js doc found out throughout the “Assets” folder. Search for the fitting code section that wants modification and exchange it as follows:

Dynamsoft.OnWebTwainNotFoundOnWindowsCallback = function(
    ProductName, 
    InstallerUrl, 
    bHTML5, 
    bIE, 
    bSafari, 
    bSSL, 
    strIEVersion
) {
    var response = {};
    response["info"] = "dynamsoft_service_not_running";
    
    window.external.notify(JSON.stringify(response));
};

With this alteration, when the ideas superhighway cyber web web page detects that Web TWAIN isn’t installed, it’s going to send a JSON-formatted message to the application.

See also  Tips on how to Customise Your WooCommerce Cart Web page for Extra Gross sales!

Inside the C# doc, use the following code to urged the individual to acquire and arrange the required supplier:

private async void WebView1_ScriptNotify(object sender, NotifyEventArgs e)
{
    var response = JsonConvert.DeserializeObject<Dictionary>(e.Value);
    string knowledge = response.GetValueOrDefault("knowledge", "");

    // Respond to the script notification
    if (knowledge == "dynamsoft_service_not_running")
    {
        // Create and set the content material subject matter of the message dialog
        var messageDialog = new MessageDialog("The Dynamsoft Supplier is not operating. Please download and arrange it.");

        // Add directions and their callbacks; each and every buttons use the an identical callback function
        messageDialog.Directions.Add(new UICommand(
            "Download",
            new UICommandInvokedHandler(this.CommandInvokedHandler)
        ));
        messageDialog.Directions.Add(new UICommand(
            "Close",
            new UICommandInvokedHandler(this.CommandInvokedHandler)
        ));

        // Set the default command
        messageDialog.DefaultCommandIndex = 0;

        // Set the cancel command
        messageDialog.CancelCommandIndex = 1;

        // Display the message dialog
        look forward to messageDialog.ShowAsync();
    }
}

private async void CommandInvokedHandler(IUICommand command)
{
    if (command.Label == "Download") 
    {
        string uriToLaunch = @"https://download2.dynamsoft.com/Demo/DWT/DWTResources/dist/DynamsoftServiceSetup.msi";
        var uri = new Uri(uriToLaunch);
        var just right fortune = look forward to House home windows.System.Launcher.LaunchUriAsync(uri);
    }
}

If the supplier isn’t vigorous, the following dialog box will appear:

Dialog Box for Inactive ServiceDialog Box for Inactive Service
Enhance Capacity with House home windows Runtime API

Some choices of Web TWAIN are limited in a WebView environment. However, by means of leveraging the House home windows Runtime API for UWP, you’ll build up the purposes of your UWP application.

The use of the Digital camera API

The Home windows.Media.Seize.CameraCaptureUI API supplies an intuitive virtual digital camera interface for taking photos images.

private async void CameraButton_Click(object sender, RoutedEventArgs e)
{
    // Benefit from the House home windows.Media.Grasp.CameraCaptureUI API to grab {a photograph}
    CameraCaptureUI dialog = new CameraCaptureUI();
    dialog.VideoSettings.AllowTrimming = true;

    StorageFile doc = look forward to dialog.CaptureFileAsync(CameraCaptureUIMode.{Photograph});
}

Once triggered, a built-in virtual digital camera dialog will appear to permit image taking photos. The API moreover provides auto-trimming choices useful for document scanning.

Built-in Camera Dialog for Image CapturingBuilt-in Camera Dialog for Image Capturing

Integrating Captured Image into WebView

You’ll have the ability to use the WebView.InvokeScriptAsync option to send the captured image to the ideas superhighway cyber web web page.

private async void CameraButton_Click(object sender, RoutedEventArgs e)
{
    // Grasp {a photograph} the use of the CameraCaptureUI API
    CameraCaptureUI dialog = new CameraCaptureUI();
    dialog.VideoSettings.AllowTrimming = true;

    StorageFile doc = look forward to dialog.CaptureFileAsync(CameraCaptureUIMode.{Photograph});

    // Convert the captured doc to a base64 string
    string base64 = look forward to StorageFileToBase64(doc);
    look forward to WebView1.InvokeScriptAsync("LoadImageFromBase64", new string[] { base64 });
}

// Convert a StorageFile to a base64 string
private async Job StorageFileToBase64(StorageFile doc)
{
    string Base64String = "";

    if (doc != null)
    {
        IRandomAccessStream fileStream = look forward to doc.OpenAsync(FileAccessMode.Be informed);
        var reader = new DataReader(fileStream.GetInputStreamAt(0));
        look forward to reader.LoadAsync((uint)fileStream.Dimension);

        byte[] byteArray = new byte[fileStream.Size];
        reader.ReadBytes(byteArray);

        Base64String = Convert.ToBase64String(byteArray);
    }

    return Base64String;
}

Displaying the Captured Image in HTML

See also  How you can Redact Textual content in WordPress (The Simple Method)

After obtaining the base64-encoded image, add it to the HTML cyber web web page the use of the following function:

function LoadImageFromBase64(base64) {
    if (DWObject) {
        DWObject.LoadImageFromBase64Binary(
            base64,
            Dynamsoft.DWT.EnumDWT_ImageType.IT_ALL
        );
    }
}
Integrating OCR Purposes

Benefit from the House home windows Media OCR API

The House home windows.Media.Ocr API supplies a very easy interface for Optical Persona Reputation (OCR). In this section, we’ll outline discover ways to add OCR purposes on your UWP application for a determined on image.

Retrieve Base64 of Determined on Image in HTML

First, add a JavaScript function to obtain the base64-encoded string of the selected image.

function GetSelectedImageInBase64() {
    if (DWObject) {
        DWObject.ConvertToBase64(
            [DWObject.CurrentImageIndexInBuffer],
            Dynamsoft.DWT.EnumDWT_ImageType.IT_PNG,
            function(finish end result, indices, type) {
                var response = {};
                response["info"] = "image_base64";
                response["data"] = finish end result.getData(0, finish end result.getLength());

                window.external.notify(JSON.stringify(response));
            },
            function(errorCode, errorString) {
                console.log(errorString);
            }
        );
    }
}

Put in force OCR Capacity in C#

Next, invoke the aforementioned JavaScript function and perform OCR on the base64-encoded image throughout the C# code.

private async void OCRButton_Click(object sender, RoutedEventArgs e)
{
    look forward to WebView1.InvokeScriptAsync("GetSelectedImageInBase64", new string[] { });
}

private async void WebView1_ScriptNotify(object sender, NotifyEventArgs e)
{
    if (knowledge == "image_base64") 
    {
        if (response.ContainsKey("data")) 
        {
            string base64 = response.GetValueOrDefault("data", "");
            OCRImageFromBase64(base64);
        }
    }
}

private async void OCRImageFromBase64(string base64)
{
    // Conversion and OCR-related not unusual sense
    // ...
    // Display OCR leads to a content material subject matter dialog
    ContentDialog contentDialog = new ContentDialog
    {
        Title = "Consequence:",
        Content material subject matter = ocrResult.Text,
        PrimaryButtonText = "Replica to clipboard",
        CloseButtonText = "Close"
    };

    ContentDialogResult finish end result = look forward to contentDialog.ShowAsync();
    if (finish end result == ContentDialogResult.Primary)
    {
        DataPackage dataPackage = new DataPackage();
        dataPackage.SetText(ocrResult.Text);
        Clipboard.SetContent(dataPackage);
    }
}

Consequence and Particular person Interaction

The OCR output might be displayed in a content material subject matter dialog box. Shoppers provide the likelihood to copy the recognized text to their clipboard.

OCR Output in Content Dialog BoxOCR Output in Content Dialog Box

Conclusion

UWP shall we in developers to build and submit versatile applications right through all House home windows units. Following the steps outlined above, you’ll create a UWP application with robust document scanning functionalities the use of the Dynamic Web TWAIN SDK.

The publish Development a UWP Report Scanning App appeared first on Hongkiat.

WordPress Website Development

Supply: https://www.hongkiat.com/blog/uwp-document-scanning-app/

[ continue ]

WordPress Maintenance Plans | WordPress Hosting

read more

0 Comments

Submit a Comment

DON'T LET YOUR WEBSITE GET DESTROYED BY HACKERS!

Get your FREE copy of our Cyber Security for WordPress® whitepaper.

You'll also get exclusive access to discounts that are only found at the bottom of our WP CyberSec whitepaper.

You have Successfully Subscribed!