Генерация изображения штрих-кода в приложении "Angular и ASP.NET Core"
В этом разделе
Данное руководство демонстрирует, как создать пустое приложение "Angular и ASP.NET Core" в Visual Studio .NET 2026 и сгенерировать изображение штрих-кода в приложении "Angular и ASP.NET Core".
Вот шаги, которые необходимо выполнить:
-
Создайте пустое приложение "Angular и ASP.NET Core".
Откройте Visual Studio .NET 2026 и создайте новый проект приложения типа "Angular and ASP.NET Core":
Настройте проект для использования .NET 10.0:
-
Проект "AngularApp1.Server": Добавьте ссылки на сборки Vintasoft в приложение ASP.NET Core.
Добавьте ссылки на nuget-пакеты "Vintasoft.Barcode", "Vintasoft.Barcode.SkiaSharp" и "Vintasoft.Barcode.AspNetCore.ApiControllers" в проект "AngularApp1.Server".
Комментарий:
Ссылка на nuget-пакет "Vintasoft.Barcode.SkiaSharp" необходима только в том случае, если SDK должен отображать текстовое значение штрих-кода на изображении штрих-кода. Вместо nuget-пакета "Vintasoft.Barcode.SkiaSharp" можно использовать nuget-пакет "Vintasoft.Barcode.ImageSharp".
-
Проект "AngularApp1.Server": Создайте веб-сервис для генерации штрихкодов.
-
Нажмите правую кнопку мыши на папке "Controllers" и выберите "Add => Controller..." в контекстном меню
-
Выберите пустой шаблон API-контроллера, задайте имя контроллера как "MyVintasoftBarcodeApiController" и нажмите кнопку "Добавить".
-
Укажите, что класс MyVintasoftBarcodeApiController является производным от класса Vintasoft.Barcode.AspNetCore.ApiControllers.VintasoftBarcodeApiController.
Вот исходный код класса MyVintasoftBarcodeApiController:
using Vintasoft.Barcode.AspNetCore.ApiControllers;
namespace WebApplication1.Controllers
{
public class MyVintasoftBarcodeApiController : VintasoftBarcodeApiController
{
public MyVintasoftBarcodeApiController(IWebHostEnvironment hostingEnvironment)
: base(hostingEnvironment)
{
}
}
}
-
Проект "AngularApp1.Server": Укажите, что VintaSoft Barcode .NET SDK должен использовать библиотеку SkiaSharp для отрисовки 2D-графики.
Откройте файл "Program.cs" в проекте "AngularApp1.Server" и добавьте строку кода "Vintasoft.Barcode.SkiaSharpAssembly.Init();" в начало файла:
Вот исходные коды файла Program.cs:
// specify that VintaSoft Barcode .NET SDK should use SkiaSharp library for drawing of 2D graphics
Vintasoft.Barcode.SkiaSharpAssembly.Init();
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllersWithViews().AddNewtonsoftJson();
var app = builder.Build();
app.UseDefaultFiles();
app.MapStaticAssets();
// Configure the HTTP request pipeline.
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.MapFallbackToFile("/index.html");
app.Run();
-
Проект "AngularApp1.Server": Удалите не нужные файлы.
Удалите файлы "WeatherForecast.cs" и "Controllers\WeatherForecastController.cs" в проекте "AngularApp1.Server" - контроллер WeatherForecast Web API не нужен в этом примере.
Проект "angularapp1.client": Скомпилируйте решение для восстановления TypeScript-зависимостей в проекте "angularapp1.client".
-
Проект "angularapp1.client": Добавьте файлы JavaScript и модули TypeScript в проект "angularapp1.client".
-
Добавьте папку "assets" в папку "src\app\" в проекте "angularapp1.client".
-
Скопируйте файлы Vintasoft.Shared.js, Vintasoft.Shared.d.ts, Vintasoft.Barcode.js и Vintasoft.Barcode.d.ts из папки "<InstallPath>\VintaSoft Barcode .NET 15.3\Bin\JavaScript\ в папку "src\app\assets\" в проекте "angularapp1.client".
-
Добавьте ссылки на файлы JavaScript Vintasoft в раздел "projects => angularapp1.client => architect => build => options => scripts" в файле "angular.json" в проекте "angularapp1.client":
...
"scripts": [
"src/app/assets/Vintasoft.Shared.js",
"src/app/assets/Vintasoft.Barcode.js"
]
...
-
Проект "angularapp1.client": Создайте компонент Angular, который распознает штрихкоды на изображении.
-
Откройте файл "src\app\app.component.html" в проекте "angularapp1.client", очистите файл, добавьте HTML-разметку (заголовок страницы и элемент изображения, который будет отображать сгенерированное изображение штрихкода) в файл "app.component.html":
<h1>Angular Barcode Generator Demo</h1>
<img id="barcodeImage" src="" />
-
Откройте файл "src\app\app.component.ts" в проекте "angularapp1.client", очистите файл, добавьте код TypeScript в файл "app.component.ts":
import { HttpClient } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
constructor(private http: HttpClient) {}
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: any) {
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: any) {
// show information about error
alert(data.errorMessage);
}
title = 'angularapp1.client';
}
-
Удалите файл "src\app\app.component.spec.ts" в проекте "angularapp1.client" - файл не нужен.
-
Откройте файл "src\proxy.conf.js" в проекте "angularapp1.client" и укажите, что приложение Angular может получить доступ к контроллеру ASP.NET Core Web API "/vintasoft/api/MyVintasoftBarcodeApi/" в проекте "AngularApp1.Server":
const { env } = require('process');
const target = env.ASPNETCORE_HTTPS_PORT ? `https://localhost:${env.ASPNETCORE_HTTPS_PORT}` :
env.ASPNETCORE_URLS ? env.ASPNETCORE_URLS.split(';')[0] : 'https://localhost:7200';
const PROXY_CONFIG = [
{
context: [
"/vintasoft/api/"
],
target,
secure: false
}
]
module.exports = PROXY_CONFIG;
-
Запустите веб-приложение "Angular и ASP.NET Core" и посмотрите результат.