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

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

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

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

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

    • Создайте новое приложение React.js с помощью следующей команды консоли:
      npx create-react-app vintasoft-web-twain-react
      
    • Перейдите в созданную папку проекта, используя следующую консольную команду:
      cd vintasoft-web-twain-react
      
  3. Скопируйте файлы Vintasoft JS и TS в приложение React.js.

    • Добавьте ссылку на npm-пакет 'vintasoft-web-twain-js' ( https://www.npmjs.com/package/vintasoft-web-twain-js ) с помощью следующей консольной команды:
      npm install vintasoft-web-twain-js
      
    • Скопируйте файлы Vintasoft.Shared.js и Vintasoft.Twain.js из папки "node_modules\vintasoft-web-twain-js\dist\" в папку "public\".

    • Добавьте ссылки на файлы Vintasoft JavaScript в файл "public\index.html":
      <!DOCTYPE html>
      <html lang="en">
        <head>
          <meta charset="utf-8" />
          <link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
          <meta name="viewport" content="width=device-width, initial-scale=1" />
          <meta name="theme-color" content="#000000" />
          <meta name="description" content="Web site created using create-react-app"/>
          <link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
          <!--
            manifest.json provides metadata used when your web app is installed on a
            user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
      -->
          <link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
          <!--
            Notice the use of %PUBLIC_URL% in the tags above.
            It will be replaced with the URL of the `public` folder during the build.
            Only files inside the `public` folder can be referenced from the HTML.
      
            Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
            work correctly both with client-side routing and a non-root public URL.
            Learn how to configure a non-root public URL by running `npm run build`.
      -->
          <title>React App</title>
      
          <script src="Vintasoft.Shared.js" type="text/javascript"></script>
          <script src="Vintasoft.Twain.js" type="text/javascript"></script>
        </head>
        <body>
          <noscript>You need to enable JavaScript to run this app.</noscript>
          <div id="root"></div>
          <!--
            This HTML file is a template.
            If you open it directly in the browser, you will see an empty page.
      
            You can add webfonts, meta tags, or analytics to this file.
            The build step will place the bundled scripts into the <body> tag.
      
            To begin the development, run `npm start` or `yarn start`.
            To create a production bundle, use `npm run build` or `yarn build`.
      -->
        </body>
      </html>
      
      
  4. Создайте компонент VintasoftWebTwain в приложении React.js.

    • Создайте папку "src\components" с помощью следующей консольной команды:
      mkdir src\components
      
    • Создайте файл "src\components\VintasoftWebTwain.js" и добавьте код компонента (элемент изображения, который отображает изображение, полученное со сканера изображений TWAIN/WIA/eSCL; код JavaScript, который получает изображение со сканера изображений TWAIN/WIA/eSCL и отображает отсканированное изображение) в файл "src\components\VintasoftWebTwain.js":
      import React, { Component } from 'react';
      
      export class VintasoftWebTwain extends Component {
          static displayName = VintasoftWebTwain.name;
      
          render() {
              return (
                  <div htmlclass="mainDiv">
                      <h1>React.js VintaSoft Web TWAIN</h1>
                      <label htmlFor="twainDeviceList">TWAIN devices:</label>
                      <select id="twainDeviceList"></select><br />
                      <br />
                      <input type="button" id="acquireImagesFromTwainDeviceButton" value="Acquire images from TWAIN device" disabled />
      
                      <h3>Preview of scanned image</h3>
                      <input type="image" id="previewImage" alt="Preview of scanned image" />
                      <br />
                      <br />
                      <a id="vintasoftWebTwainServiceInstallerLinkId" href="/Data/VSWebTwainService-15.4.0.zip" hidden>Download installer of VintaSoft Web TWAIN service</a>
                  </div>
              );
          }
      
          componentDidMount() {
              // declare reference to the Vintasoft namespace
              let Vintasoft = window.Vintasoft;
      
              // get the list of available TWAIN/WIA/eSCL devices
              __getTwainDeviceList();
      
      
              /**
               * Returns the list of available TWAIN/WIA/eSCL devices.
               */
              function __getTwainDeviceList() {
                __registerVintasoftWebTwainService();
      
                var twainDeviceManager = __openTwainDeviceManager();
                if (twainDeviceManager == null)
                  return;
      
                var twainDeviceListSelectElement = document.getElementById('twainDeviceList');
                // clear the device list
                twainDeviceListSelectElement.options.length = 0;
      
                var twainDevices = null;
                var twainDevice = 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) {
                    var acquireImagesFromTwainDeviceButton = document.getElementById("acquireImagesFromTwainDeviceButton");
                    acquireImagesFromTwainDeviceButton.disabled = false;
      
                    acquireImagesFromTwainDeviceButton.addEventListener('click', event => {
                        // acquire images from TWAIN/WIA/eSCL device
                        __acquireImagesFromTwainDevice();
                    });
                  }
                }
                catch (ex) {
                  alert(ex);
                }
                finally {
                  // close the device manager
                  twainDeviceManager.close();
                }
              }
      
              /**
               * Acquires images from TWAIN/WIA/eSCL device.
               */
              function __acquireImagesFromTwainDevice() {
                  var acquireImagesFromTwainDeviceButton = document.getElementById("acquireImagesFromTwainDeviceButton");
                  acquireImagesFromTwainDeviceButton.disabled = true;
      
                  var twainDeviceListSelectElement = document.getElementById('twainDeviceList');
                  var twainDeviceIndex = 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;
                  }            
      
                  // open TWAIN device manager
                  var twainDeviceManager = __openTwainDeviceManager();
      
                  var twainDevices = null;
                  var twainDevice = 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
                      var acquiredImages = new Vintasoft.Twain.WebAcquiredImageCollectionJS(twainDeviceManager);
                      var acquireModalState;
                      do {
                          // do one step of modal image acquisition process
                          var acquireModalResult = twainDevice.acquireModalSync();
                          // get state of image acquisition
                          acquireModalState = acquireModalResult.get_AcquireModalState().valueOf();
      
                          switch (acquireModalState) {
                              case 2:   // image is acquired
                                  // 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;
      
                              case 4:   // scan is failed
                                  alert(acquireModalResult.get_ErrorMessage());
                                  break;
      
                              case 9:   // scan is finished
                                  break;
                          }
                      }
                      while (acquireModalState !== 0);
                  }
                  catch (ex) {
                      alert(ex);
                  }
                  finally {
                      if (twainDevice != null) {
                          // close the device
                          twainDevice.close();
                      }
                      // close the device manager
                      twainDeviceManager.close();
                  }
              }
      
              function __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');
              }
      
              function __openTwainDeviceManager() {
                  // URL to the VintaSoft Web TWAIN service
                  var serviceUrl = 'https://localhost:25329/api/VintasoftTwainApi';
                  // a Web API controller that allows to work with TWAIN devices
                  var twainService = new Vintasoft.Shared.WebServiceControllerJS(serviceUrl);
      
                  // TWAIN device manager
                  var twainDeviceManager = new Vintasoft.Twain.WebTwainDeviceManagerJS(twainService);
      
                  // the default settings of TWAIN device manager
                  var deviceManagerInitSetting = new Vintasoft.Twain.WebTwainDeviceManagerInitSettingsJS();
      
                  try {
                      // open TWAIN device manager
                      twainDeviceManager.open(deviceManagerInitSetting);
                  }
                  catch (ex) {
                      if (ex.toString().startsWith('NetworkError')) {
                          document.getElementById('vintasoftWebTwainServiceInstallerLinkId').hidden = false;
                          alert("VintaSoft Web TWAIN service is not found.\n\nPlease close this dialog, link 'Download installer of VintaSoft Web TWAIN service' will appear at the top of this page, click the link, download VintaSoft Web TWAIN Service, manually install the service on your computer, reload this web page in web browser (Firefox must be restarted) and try to scan images once again.");
                      }
                      else
                          alert(ex);
                      return null;
                  }
                  return twainDeviceManager;
              }
          }
      
      }
      
      
    • Прочитайте как получить оценочную лицензию для VintaSoft TWAIN .NET SDK, здесь https://www.vintasoft.ru/docs/vstwain-dotnet-web/Licensing-Twain_Web-Evaluation.html и получите оценочную лицензию.

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

    • Укажите, что приложение React.js должно открыть компонент "VintasoftWebTwain". Для этого измените код JavaScript файла "src\App.js" на следующий код JavaScript:
      import { VintasoftWebTwain } from "./components/VintasoftWebTwain";
      
      function App() {
              return (
                      <div className="App">
                              <VintasoftWebTwain />
                      </div>
              );
      }
      
      export default App;
      
      

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

    Запустите приложение React.js с помощью следующей консольной команды:
    npm start
    

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


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