VintaSoft Barcode .NET SDK 15.0: Документация для Веб разработчика
В этом разделе
    Генерация изображения штрих-кода в приложении ASP.NET Core на Angular
    В этом разделе
    Данное руководство демонстрирует, как создать пустое веб-приложение ASP.NET Core в Visual Studio .NET 2022 и сгенерировать изображение штрих-кода в приложении ASP.NET Core на Angular.


    Вот шаги, которые необходимо выполнить:
    1. Создайте пустое веб-приложение ASP.NET Core.

      Запустите Visual Studio .NET 2022 и создайте новый проект, тип проекта - приложение ASP.NET Core на Angular:

      Включите в проекте использование .NET 8.0:

    2. Серверная сторона: Добавьте ссылки на сборки Vintasoft в веб-приложение ASP.NET Core.

      Добавьте ссылки на сборки Vintasoft.Barcode.dll, Vintasoft.Barcode.SkiaSharp.dll, Vintasoft.Shared.dll, Vintasoft.Shared.Web.dll, Vintasoft.Barcode.Web.Services.dll и Vintasoft.Barcode.AspNetCore.ApiControllers.dll из папки "<InstallPath>\VintaSoft Barcode .NET v15.0\Bin\DotNet8\AnyCPU\" в веб-приложение ASP.NET Core.
      Комментарий: Ссылка на сборку Vintasoft.Barcode.SkiaSharp.dll необходима только в том случае, если SDK должен рисовать текстовое значение штрих-кода на изображении штрих-кода. Вместо сборки Vintasoft.Barcode.SkiaSharp.dll можно использовать Vintasoft.Barcode.ImageSharp.dll.

    3. Серверная сторона: Добавьте контроллер Web API, который позволяет генерировать изображение штрих-кода.

      • Нажмите правую кнопку мыши на папке "Controllers" и выберите "Add => Controller..." в контекстном меню
      • Выберите шаблон контроллера "Empty API", задайте имя контроллера "MyVintasoftBarcodeApiController" и нажмите кнопку "Add"
      • Укажите, что класс MyVintasoftBarcodeApiController является производным от класса Vintasoft.Barcode.AspNetCore.ApiControllers.VintasoftBarcodeApiController

        Вот исходные коды класса MyVintasoftBarcodeApiController:
        using Microsoft.AspNetCore.Hosting;
        using Microsoft.AspNetCore.Mvc;
        using Vintasoft.Barcode.AspNetCore.ApiControllers;
        
        namespace Project1.Controllers
        {
            public class MyVintasoftBarcodeApiController : VintasoftBarcodeApiController
            {
        
                public MyVintasoftBarcodeApiController(IWebHostEnvironment hostingEnvironment)
                    : base(hostingEnvironment)
                {
                }
        
            }
        }
        
    4. Скомпилируйте проект с помощью NPM - это нужно для восстановления зависимостей проекта.

    5. Клиентская сторона: Удалите файлы, которые не нужны в данной демонстрации.

      Удалите директории "ClientApp\src\app\counter\", "ClientApp\src\app\fetch-data\", "ClientApp\src\app\home\", "ClientApp\src\app\nav-menu\" - эти компоненты Angular не нужны в этой демонстрации.

      Удалите файлы "WeatherForecast.cs" и "Controllers\WeatherForecastController.cs" - контроллер WeatherForecast Web API не нужен в этой демонстрации.


      Откройте файл "ClientApp\src\app\app.component.html" и удалите строку "<app-nav-menu></app-nav-menu>" из HTML-разметки - в этой демонстрации нам не нужно навигационное меню.

      Откройте файл "ClientApp\src\app\app.module.ts" и удалите код, использующий следующие компоненты Angular: NavMenuComponent, HomeComponent, CounterComponent, FetchDataComponent - эти компоненты Angular не нужны в данной демонстрации.
      Вот исходные коды файла "app.module.ts" после обновления:
      import { BrowserModule } from '@angular/platform-browser';
      import { NgModule } from '@angular/core';
      import { FormsModule } from '@angular/forms';
      import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
      import { RouterModule } from '@angular/router';
      
      import { AppComponent } from './app.component';
      
      @NgModule({
        declarations: [
          AppComponent,
        ],
        imports: [
          BrowserModule.withServerTransition({ appId: 'ng-cli-universal' }),
          HttpClientModule,
          FormsModule,
          RouterModule.forRoot([
          ])
        ],
        providers: [],
        bootstrap: [AppComponent]
      })
      export class AppModule { }
      
      
    6. Клиентская сторона: Добавьте файлы JavaScript и модули TypeScript в веб-приложение ASP.NET Core.

      Добавьте папку "assets" в папку "ClientApp\src\app\".

      Скопируйте файлы Vintasoft.Shared.js, Vintasoft.Shared.d.ts, Vintasoft.Barcode.js и Vintasoft.Barcode.d.ts из папки "<InstallPath>\VintaSoft Barcode .NET v15.0\Bin\JavaScript\" в папку "ClientApp\src\app\assets\".

      Установите "Build Action" на "TypeScript file" для файлов Vintasoft.Shared.d.ts и Vintasoft.Barcode.d.ts:


      Добавьте ссылки на файлы Vintasoft JavaScript в раздел "projects => Demo => architect => build => options => scripts" файла "ClientApp\angular.json":
      ...
      "scripts": [
        "src/app/assets/Vintasoft.Shared.js",
        "src/app/assets/Vintasoft.Barcode.js"
      ]
      ...
      

    7. Клиентская сторона: Создайте компонент Angular, который генерирует и отображает изображение штрих-кода.

      • Создайте папку "ClientApp\src\app\barcode-generator-demo\".

        Создайте файл "barcode-generator-demo.component.html", который будет содержать HTML-разметку компонента Angular:
        • Выберите "Add => New Item..." в контекстном меню папки "ClientApp\src\app\barcode-generator-demo\" => Откроется диалог "Add new item"
        • Выберите тип нового элемента "HTML Page"
        • Задайте имя элемента "barcode-generator-demo.component.html"
        • Нажмите кнопку "Add" => Диалог будет закрыт, а файл "barcode-generator-demo.component.html" будет добавлен в папку "ClientApp\src\app\barcode-generator-demo\"

        Добавьте в файл "barcode-generator-demo.component.html" HTML-разметку (заголовок страницы и элемент image, который будет отображать сгенерированное изображение штрих-кода):
        <h1>Angular Barcode Generator Demo</h1>
        
        <img id="barcodeImage" src="" />
        
        


        Создайте файл "barcode-generator-demo.component.ts", который будет содержать код компонента Angular:
        • Выберите "Add => New Item..." в контекстном меню папки "ClientApp\src\app\barcode-generator-demo\" => Откроется диалог "Add new item"
        • Выберите тип нового элемента "TypeScript File"
        • Задайте имя элемента "barcode-generator-demo.component.ts"
        • Нажмите на кнопку "Add" => Диалог будет закрыт, а файл "barcode-generator-demo.component.ts" будет добавлен в папку "ClientApp\src\app\barcode-generator-demo\"

        Добавьте код TypeScript в файл "barcode-generator-demo.component.cs":
        import { Component } from '@angular/core';
        
        @Component({
          selector: 'barcode-generator-demo',
          templateUrl: './barcode-generator-demo.component.html'
        })
        export class BarcodeGeneratorDemoComponent {
        
          ngOnInit() {
            // generate image of QR barcode with value "12345"
            this.generate2dBarcodeImage("QR", "12345");
          }
        
          /**
           * Generates 1D barcode image.
           * @param barcodeType Barcode type.
           * @param barcodeValue Barcode value.
          */
          public generate1dBarcodeImage(barcodeType: string, barcodeValue: string) {
            // set the session identifier
            Vintasoft.Shared.WebImagingEnviromentJS.set_SessionId("SessionID");
        
            // create web service that allows to generate barcode
            let barcodeService: Vintasoft.Shared.WebServiceJS = new Vintasoft.Shared.WebServiceControllerJS("vintasoft/api/MyVintasoftBarcodeApi");
        
            // create the barcode writer
            let barcodeWriter: Vintasoft.Barcode.WebBarcodeWriterJS = new Vintasoft.Barcode.WebBarcodeWriterJS(barcodeService);
        
            // create the barcode writer settings for generating 2D barcode
            let barcodeWriterSettings: Vintasoft.Barcode.Web1DBarcodeWriterSettingsJS = new Vintasoft.Barcode.Web1DBarcodeWriterSettingsJS();
            // specify that barcode writer must generate QR barcode image
            barcodeWriterSettings.set_BarcodeType(new Vintasoft.Barcode.WebBarcodeTypeEnumJS(barcodeType));
            // specify the QR barcode value
            barcodeWriterSettings.set_Value(barcodeValue);
        
            // specify settings for barcode writer
            barcodeWriter.set_Settings(barcodeWriterSettings);
        
            // send an asynchronous request for getting barcode image as Base64 string
            barcodeWriter.getBarcodeAsBase64Image(this.__writeBarcode_success, this.__writeBarcode_failed);
          }
        
          /**
           * Generates 2D barcode image.
           * @param barcodeType Barcode type.
           * @param barcodeValue Barcode value.
          */
          public generate2dBarcodeImage(barcodeType: string, barcodeValue: string) {
            // set the session identifier
            Vintasoft.Shared.WebImagingEnviromentJS.set_SessionId("SessionID");
        
            // create web service that allows to generate barcode
            let barcodeService: Vintasoft.Shared.WebServiceJS = new Vintasoft.Shared.WebServiceControllerJS("vintasoft/api/MyVintasoftBarcodeApi");
        
            // create the barcode writer
            let barcodeWriter: Vintasoft.Barcode.WebBarcodeWriterJS = new Vintasoft.Barcode.WebBarcodeWriterJS(barcodeService);
        
            // create the barcode writer settings for generating 2D barcode
            let barcodeWriterSettings: Vintasoft.Barcode.Web2DBarcodeWriterSettingsJS = new Vintasoft.Barcode.Web2DBarcodeWriterSettingsJS();
            // specify that barcode writer must generate QR barcode image
            barcodeWriterSettings.set_BarcodeType(new Vintasoft.Barcode.WebBarcodeTypeEnumJS(barcodeType));
            // specify the QR barcode value
            barcodeWriterSettings.set_Value(barcodeValue);
        
            // specify settings for barcode writer
            barcodeWriter.set_Settings(barcodeWriterSettings);
        
            // send an asynchronous request for getting barcode image as Base64 string
            barcodeWriter.getBarcodeAsBase64Image(this.__writeBarcode_success, this.__writeBarcode_failed);
          }
        
          /**
           * Barcode is generated successfully.
           * @param data Object that stores response from barcode service.
           */
          private __writeBarcode_success(data: Vintasoft.Barcode.WebBarcodeWriteResponseParamsJS) {
            if (data.success) {
              let barcodeImage: string = data.barcodeImage;
              let barcodeImageElement: HTMLImageElement = document.getElementById("barcodeImage") as HTMLImageElement;
              barcodeImageElement.src = barcodeImage;
            }
            else {
              alert(data.errorMessage);
            }
          }
        
          /**
           * Barcode generation is failed.
           * @param data Object with information about error.
           */
          private __writeBarcode_failed(data) {
            // show information about error
            alert(data.errorMessage);
          }
        
        }
        
        


      • Добавьте созданный компонент Angular в модуль приложения Angular - файл "ClientApp\src\app\app.module.ts".


        Вот исходные коды файла "app.module.ts" после обновления:
        import { BrowserModule } from '@angular/platform-browser';
        import { NgModule } from '@angular/core';
        import { FormsModule } from '@angular/forms';
        import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
        import { RouterModule } from '@angular/router';
        
        import { AppComponent } from './app.component';
        import { BarcodeGeneratorDemoComponent } from './barcode-generator-demo/barcode-generator-demo.component';
        
        @NgModule({
          declarations: [
            AppComponent,
            BarcodeGeneratorDemoComponent
          ],
          imports: [
            BrowserModule.withServerTransition({ appId: 'ng-cli-universal' }),
            HttpClientModule,
            FormsModule,
            RouterModule.forRoot([
              { path: '', component: BarcodeGeneratorDemoComponent, pathMatch: 'full' },
            ])
          ],
          providers: [],
          bootstrap: [AppComponent]
        })
        export class AppModule { }
        
        
    8. Запустите веб-приложение ASP.NET Core на Angular и оцените результат.