VintaSoft Twain .NET SDK 15.4: Документация для Веб разработчика
В этом разделе
Асинхронное получение изображений от TWAIN/WIA/SANE/eSCL сканера изображений
В этом разделе
VintaSoft Twain .NET SDK позволяет получать изображения от TWAIN/WIA/SANE/eSCL сканера изображений асинхронно.

Вот список шагов, которые необходимо выполнить для асинхронного получения изображений от TWAIN/SANE сканера изображений:
  1. Откройте менеджер устройств TWAIN/WIA/SANE/eSCL.
  2. Выберите TWAIN/WIA/SANE/eSCL устройство.
  3. Откройте TWAIN/WIA/SANE/eSCL устройство.
  4. Установите параметры сканирования для TWAIN/WIA/SANE/eSCL устройства.
  5. Начните асинхронный процесс получения изображений, вызвав функцию WebTwainDeviceJS.acquireModalAsync.
  6. Получите отсканированное изображение, если функция WebTwainDeviceJS.acquireModalAsync вернула значение WebTwainAcquireModalStateEnumJS.ImageAcquired.
  7. Прервите цикл, если функция WebTwainDeviceJS.acquireModalAsync вернула значение WebTwainAcquireModalStateEnumJS.None.

Вот JavaScript код, который демонстрирует как асинхронно получить изображения от TWAIN/WIA/SANE/eSCL сканера изображений и сохранить полученные изображения в PDF документ:
// TWAIN device manager
var _deviceManager;
// TWAIN device
var _device = null;
// a collection that stores images, which are acquired from TWAIN/WIA/SANE/eSCL devices and stored in memory of VintaSoft Web TWAIN service
var _acquiredImages;


// asynchronously acquire images from TWAIN/WIA/SANE/eSCL image scanner and saves acquired images to PDF file
__asynchronouslyAcquireImagesFromTwainScannerAndSaveToPdfFile();


/**
 * Asynchronously acquires images from TWAIN/WIA/SANE/eSCL image scanner and saves acquired images to PDF file.
 */
function __asynchronouslyAcquireImagesFromTwainScannerAndSaveToPdfFile() {
    // 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');

    // URL to the VintaSoft Web TWAIN service
    var serviceUrl = 'https://localhost:25329/api/VintasoftTwainApi';
    // a Web API controller that allows to work with TWAIN/WIA/SANE/eSCL devices
    var twainService = new Vintasoft.Shared.WebServiceControllerJS(serviceUrl);

    // TWAIN/WIA/SANE/eSCL device manager
    _deviceManager = new Vintasoft.Twain.WebTwainDeviceManagerJS(twainService);
    // create a collection that stores images, which are acquired from TWAIN/WIA/SANE/eSCL devices and stored in memory of VintaSoft Web TWAIN service
    _acquiredImages = new Vintasoft.Twain.WebAcquiredImageCollectionJS(_deviceManager);

    // the default settings of device manager
    var deviceManagerInitSetting = new Vintasoft.Twain.WebTwainDeviceManagerInitSettingsJS();

    try {
        // open device manager
        _deviceManager.open(deviceManagerInitSetting);

        // get the default TWAIN/WIA/SANE/eSCL device
        _device = _deviceManager.get_DefaultDevice();

        // open device
        _device.open(false);

        // do one step of modal image acquisition process
        _device.acquireModalAsync(__acquireModal_success, __acquireModal_error);
    }
    catch (ex) {
        alert(ex);
    }
}

/**
 * One image scanning iteration is executed successfully.
 * @param {object} twainDevice An instance of WebTwainDeviceJS class.
 * @param {object} acquireModalResult An instance of WebTwainDeviceAcquireModalResultJS class.
 */
function __acquireModal_success(twainDevice, acquireModalResult) {
    // get the state of image scanning
    var acquireModalStateValue = acquireModalResult.get_AcquireModalState().valueOf();
    switch (acquireModalStateValue) {
        // if image is acquired
        case 2:
            // get acquired image
            var acquiredImage = acquireModalResult.get_AcquiredImage();
            // add acquired image to the image collection
            _acquiredImages.add(acquiredImage);

            // get image as Base64 string
            var bitmapAsBase64String = acquiredImage.getAsBase64String();
            // update image preview
            var previewImageElement = document.getElementById('previewImage');
            previewImageElement.src = bitmapAsBase64String;

            // clear image collection (delete images from memory of VintaSoft Web TWAIN service) because image is not necessary anymore
            _acquiredImages.clear();
            break;

        // if image scanning is failed
        case 4:
            alert(acquireModalResult.get_ErrorMessage());
            break;

        // if image scanning is canceled
        case 5:
            alert('Scan is canceled.');
            break;

        // if image scanning is finished
        case 9:
            break;
    }

    // if modal image acquisition process is not finished and must be continued
    if (acquireModalStateValue !== 0) {
        // send asynchronous request for doing one step of modal image acquisition process
        _device.acquireModalAsync(__acquireModal_success, __acquireModal_error);
    }
    // if image scanning is finished
    else {
        // close device manager
        __closeTwainDeviceManager();
    }
}

/**
 * One image scanning iteration is failed.
 * @param {object} data Information about error.
 */
function __acquireModal_error(data) {
    alert('Acquire modal error: ' + data);
}

/**
 * Closes TWAIN/WIA/SANE/eSCL device manager.
 */
function __closeTwainDeviceManager() {
    if (_device != null) {
        // close the device
        _device.close();
    }
    // close the device manager
    _deviceManager.close();
}



Вот TypeScript код, который демонстрирует как асинхронно получить изображения от TWAIN/WIA/SANE/eSCL сканера изображений и сохранить полученные изображения в PDF документ:
import { Component } from '@angular/core';


var _twainScanningDemoComponent: TwainScanningDemoComponent;


@Component({
  selector: 'twain-scanning-demo',
  templateUrl: './twain-scanning-demo.component.html'
})
export class TwainScanningDemoComponent {

  // TWAIN device manager
  _twainDeviceManager: Vintasoft.Twain.WebTwainDeviceManagerJS;
  // TWAIN device
  _twainDevice: Vintasoft.Twain.WebTwainDeviceJS;
  // a collection that stores images, which are acquired from TWAIN/WIA/SANE/eSCL devices and stored in memory of VintaSoft Web TWAIN service
  _acquiredImages: Vintasoft.Twain.WebAcquiredImageCollectionJS;


  ngOnInit() {
    _twainScanningDemoComponent = this;

    // asynchronously acquire images from TWAIN/WIA/SANE/eSCL image scanner and saves acquired images to PDF file
    this.__asynchronouslyAcquireImagesFromTwainScannerAndSaveToPdfFile();
  }


  /**
   * Asynchronously acquires images from TWAIN/WIA/SANE/eSCL image scanner and saves acquired images to PDF file.
   */
  __asynchronouslyAcquireImagesFromTwainScannerAndSaveToPdfFile() {
    // 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');

    // 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/WIA/SANE/eSCL devices
    let twainService: Vintasoft.Shared.WebServiceControllerJS = new Vintasoft.Shared.WebServiceControllerJS(serviceUrl);

    // TWAIN/WIA/SANE/eSCL device manager
    this._twainDeviceManager = new Vintasoft.Twain.WebTwainDeviceManagerJS(twainService);
    // create a collection that stores images, which are acquired from TWAIN/WIA/SANE/eSCL devices and stored in memory of VintaSoft Web TWAIN service
    this._acquiredImages = new Vintasoft.Twain.WebAcquiredImageCollectionJS(this._twainDeviceManager);

    // the default settings of device manager
    let deviceManagerInitSetting: Vintasoft.Twain.WebTwainDeviceManagerInitSettingsJS = new Vintasoft.Twain.WebTwainDeviceManagerInitSettingsJS();

    try {
      // open device manager
      this._twainDeviceManager.open(deviceManagerInitSetting);
    }
    catch (ex) {
      alert(ex);
      return;
    }

    try {
      // get the default TWAIN/WIA/SANE/eSCL device
      this._twainDevice = this._twainDeviceManager.get_DefaultDevice();

      // open device without UI
      this._twainDevice.open(false);

      // do one step of modal image acquisition process
      this._twainDevice.acquireModalAsync(this.__acquireModal_success, this.__acquireModal_error);
    }
    catch (ex) {
      alert(ex);
    }
  }

  /**
   * One image scanning iteration is executed successfully.
   * @param twainDevice An instance of WebTwainDeviceJS class.
   * @param acquireModalResult An instance of WebTwainDeviceAcquireModalResultJS class.
   */
  __acquireModal_success(twainDevice, acquireModalResult) {
    // get the state of TWAIN image scanning
    var acquireModalStateValue = acquireModalResult.get_AcquireModalState().valueOf();
    switch (acquireModalStateValue) {
      // if image is acquired
      case 2:
        // get acquired image
        let acquiredImage: Vintasoft.Twain.WebAcquiredImageJS = acquireModalResult.get_AcquiredImage();
        // add acquired image to the image collection
        this._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
        this._acquiredImages.clear();
        break;

      // if image scanning is failed
      case 4:
        alert(acquireModalResult.get_ErrorMessage());
        break;

      // if image scanning is canceled
      case 5:
        alert('Scan is canceled.');
        break;

      // if image scanning is finished
      case 9:
        break;
    }

    // if modal image acquisition process is not finished and must be continued
    if (acquireModalStateValue !== 0) {
      // send asynchronous request for doing one step of modal image acquisition process
      _twainScanningDemoComponent._twainDevice.acquireModalAsync(_twainScanningDemoComponent.__acquireModal_success, _twainScanningDemoComponent.__acquireModal_error);
    }
    // if image scanning is finished
    else {
      // close device manager
      _twainScanningDemoComponent.__closeTwainDeviceManager();
    }
  }

  /**
   One image scanning iteration is failed.
   @param {object} data Information about error.
  */
  __acquireModal_error(data) {
    alert('Acquire modal error: ' + data);
  }

  /**
   * Closes TWAIN/WIA/SANE/eSCL device manager.
   */
  __closeTwainDeviceManager() {
    if (_twainScanningDemoComponent._twainDevice != null) {
      // close the device
      _twainScanningDemoComponent._twainDevice.close();
    }
    // close the device manager
    _twainScanningDemoComponent._twainDeviceManager.close();
  }

}