VintaSoft Twain .NET SDK 15.5: Документация для Веб разработчика
В этом разделе
Получение изображений со сканера изображений TWAIN/WIA/eSCL в приложении Angular
В этом разделе
В этом руководстве показано, как создать новое приложение Angular, позволяющее получать изображения со сканера изображений TWAIN/WIA/eSCL в Windows.

Вот действия, которые необходимо выполнить:
  1. Установите Node.js и npm клиента на Ваш компьютер.

    • Вам необходимо создать приложение Angular с помощью Node.js . Пожалуйста, установите Node.js на Ваш компьютер, если Node.js ещё не установлен.

    • Инсталлятор Node.js установит также npm клиента по умолчанию.

  2. Создайте новое Angular приложение.

    • Создайте новое Angular приложение, используя следующую консольную команду:
      ng new web-twain-scanning-angular-tutorial
      
    • Используйте настройки по умолчанию для созданного приложения.

    • Перейдите в созданную папку проекта, используя следующую консольную команду:
      cd web-twain-scanning-angular-tutorial
      
  3. Скопируйте Vintasoft JS- и TS-файлы в Angular приложение.

    • Добавьте ссылку на npm-пакет 'vintasoft-web-twain-js' ( https://www.npmjs.com/package/vintasoft-web-twain-js ) с помощью следующей консольной команды:
      npm install vintasoft-web-twain-js
      
    • Создайте папку "src\app\assets", используя следующую консольную команду:
      mkdir src\app\assets
      
    • Copy Vintasoft.Shared.js, Vintasoft.Twain.js, Vintasoft.Shared.d.ts and Vintasoft.Twain.d.ts files from folder "node_modules\vintasoft-web-twain-js\dist\" to the folder "src\app\assets\".

    • Добавьте ссылки на Vintasoft JavaScript файлы к секции "projects => vintasoft-web-twain-angular => architect => build => options => scripts" в файле "angular.json":
      {
        "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
        "version": 1,
        "newProjectRoot": "projects",
        "projects": {
          "web-twain-scanning-angular-tutorial": {
            "projectType": "application",
            "schematics": {},
            "root": "",
            "sourceRoot": "src",
            "prefix": "app",
            "architect": {
              "build": {
                "builder": "@angular-devkit/build-angular:browser",
                "options": {
                  "outputPath": "dist/web-twain-scanning-angular-tutorial",
                  "index": "src/index.html",
                  "main": "src/main.ts",
                  "polyfills": [
                    "zone.js"
                  ],
                  "tsConfig": "tsconfig.app.json",
                  "assets": [
                    "src/favicon.ico",
                    "src/assets"
                  ],
                  "styles": [
                    "src/styles.css"
                  ],
                  "scripts": [
                    "src/app/assets/Vintasoft.Shared.js",
                    "src/app/assets/Vintasoft.Twain.js"
                  ]
                },
      ...
      
  4. Создайте vintasoft-web-twain компонент в Angular приложении.

    • Добавьте новый компонент в Angular приложение, используя следующую консольную команду:
      ng generate component web-twain-scanning-angular-tutorial
      
    • Добавьте HTML-разметку (элемент изображения, который будет отображать изображение, полученное со сканера изображений TWAIN/WIA/eSCL) в файл "src\app\web-twain-scanning-angular-tutorial.component.html":
      <div style="text-align:center">
        <h1>Web TWAIN Scanning Tutorial for Angular</h1>
        <label for="twainDeviceList">TWAIN devices:</label>
        <select id="twainDeviceList"></select><br />
        <br />
        <input type="button" id="acquireImagesFromTwainDeviceButton" value="Acquire images from TWAIN device" disabled (click)="acquireImagesFromTwainDevice()" />
      
        <h3>Preview of scanned image</h3>
        <input type="image" id="previewImage" alt="Preview of scanned image" style="border:1px solid black; width:350px; height:350px" />
        <br />
        <br />
        <a href="https://www.vintasoft.ru/docs/vstwain-dotnet-web/Licensing-Twain_Web-Evaluation.html" target="_blank">Read how to get the evaluation license</a><br />
        <a href="/assets/VSWebTwainService-15.5.1.zip">Download installer of VintaSoft Web TWAIN service</a><br />
      </div>
      
      
    • Добавьте код TypeScript, который получает изображение со сканера изображений TWAIN/WIA/eSCL и отображает его, в файл "src\app\web-twain-scanning-angular-tutorial.component.ts":
      import { Component } from '@angular/core';
      
      @Component({
        selector: 'app-web-twain-scanning-angular-tutorial',
        templateUrl: './web-twain-scanning-angular-tutorial.component.html',
        styleUrls: ['./web-twain-scanning-angular-tutorial.component.css']
      })
      export class WebTwainScanningAngularTutorialComponent {
      
        constructor() {
        }
      
      
      
        ngOnInit() {
          // acquire images from TWAIN/WIA/eSCL image scanner
          this.getTwainDeviceList();
        }
      
      
        /**
        * Acquires images from TWAIN/WIA/eSCL image scanner.
        */
        getTwainDeviceList() {
          this.__registerVintasoftWebTwainService();
      
          let twainDeviceManager: Vintasoft.Twain.WebTwainDeviceManagerJS | null = this.__openTwainDeviceManager();
          if (twainDeviceManager == null)
            return;
      
          let twainDeviceListSelectElement: HTMLSelectElement = document.getElementById('twainDeviceList') as HTMLSelectElement;
          // clear the device list
          twainDeviceListSelectElement.options.length = 0;
      
          let twainDevices: Vintasoft.Twain.WebTwainDeviceJS[] | null = null;
          let twainDevice: Vintasoft.Twain.WebTwainDeviceJS | null = null;
          try {
            // get an array of available TWAIN devices
            twainDevices = twainDeviceManager.get_Devices();
      
            // get the default TWAIN device
            twainDevice = twainDeviceManager.get_DefaultDevice();
      
            // for each TWAIN device
            for (var i = 0; i < twainDevices.length; i++) {
                // add the device info to the device list
                twainDeviceListSelectElement.options.length = twainDeviceListSelectElement.options.length + 1;
                twainDeviceListSelectElement.options[i].text = twainDevices[i].get_DeviceName();
                // if device is default device
                if (twainDevices[i].get_DeviceName() === twainDevice.get_DeviceName())
                    // select device in device selection element
                    twainDeviceListSelectElement.options[i].selected = true;
            }
      
            if (twainDevices.length > 0) {
              let acquireImagesFromTwainDeviceButton: HTMLButtonElement = document.getElementById("acquireImagesFromTwainDeviceButton") as HTMLButtonElement;
              acquireImagesFromTwainDeviceButton.disabled = false;
            }
          }
          catch (ex) {
            alert(ex);
          }
          finally {
            if (twainDevice != null) {
              // close the device
              twainDevice.close();
            }
            // close the device manager
            twainDeviceManager.close();
          }
        }
      
        acquireImagesFromTwainDevice() {
          let acquireImagesFromTwainDeviceButton: HTMLButtonElement = document.getElementById("acquireImagesFromTwainDeviceButton") as HTMLButtonElement;
          acquireImagesFromTwainDeviceButton.disabled = true;
      
          let twainDeviceListSelectElement: HTMLSelectElement = document.getElementById('twainDeviceList') as HTMLSelectElement;
          let twainDeviceIndex: number = twainDeviceListSelectElement.selectedIndex;
          // if TWAIN device manager does not have TWAIN devices
          if (twainDeviceIndex == -1) {
            alert('TWAIN device manager does not have TWAIN devices.');
            acquireImagesFromTwainDeviceButton.disabled = false;
            return;
          }
      
          var twainDeviceName = twainDeviceListSelectElement.value;
          if (twainDeviceName == null) {
            alert('TWAIN device name is not found.');
            acquireImagesFromTwainDeviceButton.disabled = false;
            return;
          }
      
          this.__registerVintasoftWebTwainService();
      
          let twainDeviceManager: Vintasoft.Twain.WebTwainDeviceManagerJS | null = this.__openTwainDeviceManager();
          if (twainDeviceManager == null) {
            alert('TWAIN device manager is not found.');
            acquireImagesFromTwainDeviceButton.disabled = false;
            return;
          }
      
          let twainDevices: Vintasoft.Twain.WebTwainDeviceJS[] | null = null;
          let twainDevice: Vintasoft.Twain.WebTwainDeviceJS | null = null;
          try {
            // get an array of available TWAIN devices
            twainDevices = twainDeviceManager.get_Devices();
      
            // for each TWAIN device
            for (var i = 0; i < twainDevices.length; i++) {
                if (twainDevices[i].get_DeviceName() === twainDeviceName)
                    twainDevice = twainDevices[i];
            }
      
            if (twainDevice == null) {
              alert('TWAIN device is not found.');
              acquireImagesFromTwainDeviceButton.disabled = false;
              return;
            }
      
            // open TWAIN device (do not display device UI but display dialog with image scanning progress)
            twainDevice.open(false, true);
      
            // a collection that stores images, which are acquired from devices and stored in memory of VintaSoft Web TWAIN service
            let acquiredImages: Vintasoft.Twain.WebAcquiredImageCollectionJS = new Vintasoft.Twain.WebAcquiredImageCollectionJS(twainDeviceManager);
            let acquireModalState: number;
            do {
              // do one step of modal image acquisition process
              let acquireModalResult: Vintasoft.Twain.WebTwainDeviceAcquireModalResultJS = twainDevice.acquireModalSync();
              // get state of image acquisition
              acquireModalState = acquireModalResult.get_AcquireModalState().valueOf() as number;
      
              switch (acquireModalState) {
                case 2:   // image is acquired
                  // get acquired image
                  let acquiredImage: Vintasoft.Twain.WebAcquiredImageJS = acquireModalResult.get_AcquiredImage();
                  // add acquired image to the image collection
                  acquiredImages.add(acquiredImage);
      
                  // get image as Base64 string
                  let bitmapAsBase64String: string = acquiredImage.getAsBase64String();
                  // update image preview
                  let previewImageElement: HTMLImageElement = document.getElementById('previewImage') as HTMLImageElement;
                  previewImageElement.src = bitmapAsBase64String;
      
                  // clear image collection (delete images from memory of VintaSoft Web TWAIN service) because image is not necessary anymore
                  acquiredImages.clear();
                  break;
      
                case 4:   // scan is failed
                  alert(acquireModalResult.get_ErrorMessage());
                  break;
      
                case 9:   // scan is finished
                  break;
              }
            }
            while (acquireModalState !== 0);
          }
          catch (ex) {
            alert(ex);
          }
          finally {
            acquireImagesFromTwainDeviceButton.disabled = false;
            if (twainDevice != null) {
              // close the device
              twainDevice.close();
            }
            // close the device manager
            twainDeviceManager.close();
          }
        }
      
        __registerVintasoftWebTwainService() {
          // register the evaluation version of VintaSoft Web TWAIN service
          // please read how to get evaluation license in documentation: https://www.vintasoft.ru/docs/vstwain-dotnet-web/Licensing-Twain_Web-Evaluation.html
          Vintasoft.Twain.WebTwainGlobalSettingsJS.register('REG_USER', 'REG_URL', 'REG_CODE', 'EXPIRATION_DATE');
        }
      
        __openTwainDeviceManager(): Vintasoft.Twain.WebTwainDeviceManagerJS | null {
          // URL to the VintaSoft Web TWAIN service
          let serviceUrl: string = 'https://localhost:25329/api/VintasoftTwainApi';
          // a Web API controller that allows to work with TWAIN devices
          let twainService: Vintasoft.Shared.WebServiceControllerJS = new Vintasoft.Shared.WebServiceControllerJS(serviceUrl);
      
          // TWAIN device manager
          let twainDeviceManager: Vintasoft.Twain.WebTwainDeviceManagerJS = new Vintasoft.Twain.WebTwainDeviceManagerJS(twainService);
      
          // the default settings of TWAIN device manager
          let deviceManagerInitSetting: Vintasoft.Twain.WebTwainDeviceManagerInitSettingsJS = new Vintasoft.Twain.WebTwainDeviceManagerInitSettingsJS();
      
          try {
            // open TWAIN device manager
            twainDeviceManager.open(deviceManagerInitSetting);
          }
          catch (ex) {
            alert(ex);
            return null;
          }
          return twainDeviceManager;
        }
      
      }
      
      
    • Прочитайте как получить оценочную лицензию для VintaSoft TWAIN .NET SDK, здесь https://www.vintasoft.ru/docs/vstwain-dotnet-web/Licensing-Twain_Web-Evaluation.html и получите оценочную лицензию.

    • Вставьте TypeScript код с оценочной лицензией вместо строки кода"Vintasoft.Twain.WebTwainGlobalSettingsJS.register('REG_USER', 'REG_URL', 'REG_CODE', 'EXPIRATION_DATE');" в файл vintasoft-web-twain.component.ts.

    • Укажите, что Angular приложение должно открывать компонент "web-twain-scanning-angular-tutorial". Для этого, пожалуйста, измените HTML-код файла "src\app.component.html" на следующий HTML-код:
      <app-web-twain-scanning-angular-tutorial></app-web-twain-scanning-angular-tutorial>
      

  5. Запустите Angular приложение и посмотрите результат.

    Запустите Angular приложение, используя следующую консольную команду:
    ng serve -o
    

    Если VintaSoft Web TWAIN сервис установлен на Ваш компьютер, Вы увидите следующий результат:


    Если VintaSoft Web TWAIN сервис не установлен на Вашем компьютере (Вы увидите сообщение об ошибке), Вам нужно выполнить следующие действия:
    • нажмите на ссылку "Загрузить инсталлятор VintaSoft Web TWAIN сервиса"
    • загрузите инсталлятор VintaSoft Web TWAIN сервиса на Ваш компьютер
    • установите VintaSoft Web TWAIN сервис на Ваш компьютер
    • обновите страницу приложения в браузере

Готовый к использованию проект из этого руководства можно загрузить с Github: https://github.com/vintasoft/web-twain-scanning-angular-tutorial .