Генерация изображения штрих-кода в приложении "React.js и ASP.NET Core"
В этом разделе
Данное руководство демонстрирует, как создать пустое приложение "React.js и ASP.NET Core" в Visual Studio .NET 2026 и сгенерировать изображение штрих-кода в приложении "React.js и ASP.NET Core".
Вот шаги, которые необходимо выполнить:
-
Создайте пустое приложение "React.js и ASP.NET Core".
Откройте Visual Studio .NET 2026 и создайте новый проект типа "приложение React.js и ASP.NET Core":
Настройте проект для использования .NET 10.0:
-
Проект "ReactApp1.Server": Добавьте ссылки на nuget-пакеты Vintasoft в приложение ASP.NET Core.
Добавьте ссылки на nuget-пакеты "Vintasoft.Barcode", "Vintasoft.Barcode.SkiaSharp" и "Vintasoft.Barcode.AspNetCore.ApiControllers" в проект "ReactApp1.Server".
Комментарий:
Ссылка на nuget-пакет "Vintasoft.Barcode.SkiaSharp" необходима только в том случае, если SDK должен отображать текстовое значение штрих-кода на изображении штрих-кода. Вместо nuget-пакета "Vintasoft.Barcode.SkiaSharp" можно использовать nuget-пакет "Vintasoft.Barcode.ImageSharp".
-
Проект "ReactApp1.Server": Добавьте контроллер Web API, позволяющий генерировать изображение штрих-кода.
-
Нажмите правую кнопку мыши на папке "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)
{
}
}
}
-
Проект "ReactApp1.Server": Удалите не нужные файлы.
Удалите файлы "ReactApp1.Server.http", "WeatherForecast.cs" и "Controllers\WeatherForecastController.cs" в проекте "ReactApp1.Server" - контроллер Web API WeatherForecast в этом примере не нужен.
Проект "reactapp1.client": Скомпилируйте решение для восстановления зависимостей TypeScript в проекте "reactapp1.client".
-
Проект "reactapp1.client": Добавьте файлы JavaScript в приложение ASP.NET Core.
-
Скопируйте файлы Vintasoft.Shared.js и Vintasoft.Barcode.js из папки "\VintaSoft Barcode .NET 15.3\Bin\JavaScript\" в папку "public" в проекте "reactapp1.client".
-
Добавьте ссылки на файлы JavaScript Vintasoft в заголовок файла "index.html" в проекте "reactapp1.client":
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>reactapp1.client</title>
<script src="Vintasoft.Shared.js" type="text/javascript"></script>
<script src="Vintasoft.Barcode.js" type="text/javascript"></script>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.jsx"></script>
</body>
</html>
-
Проект "reactapp1.client": Создайте компонент React.js, который генерирует изображение штрих-кода и отображает его.
-
Откройте файл "src\App.jsx" в проекте "reactapp1.client", очистите файл, добавьте код JavaScript в файл "App.jsx" (функция "App" генерирует разметку страницы и запускает генерацию изображения штрих-кода, функция "__generateBarcode" генерирует изображение штрих-кода):
Вот код JavaScript из файла App.jsx:
import './App.css'
function App() {
return (
<>
<div>
<h1>Angular Barcode Generator Demo</h1>
<img id="barcodeImage" src="" />
</div>
<script>{setTimeout(__generateBarcode, 10)}</script>
</>
)
}
/**
* Generates barcode image.
*/
function __generateBarcode() {
// generate image of QR barcode with value "12345"
__generate2dBarcodeImage("QR", "12345");
}
/**
* Generates 1D barcode image.
* @param barcodeType Barcode type.
* @param barcodeValue Barcode value.
*/
function __generate1dBarcodeImage(barcodeType, barcodeValue) {
try {
// declare reference to the Vintasoft namespace
var Vintasoft = window.Vintasoft;
if (Vintasoft.Shared.WebImagingEnviromentJS.get_SessionId() == null)
// set the session identifier
Vintasoft.Shared.WebImagingEnviromentJS.set_SessionId("SessionID");
// create web service that allows to generate barcode
var barcodeService = new Vintasoft.Shared.WebServiceControllerJS("vintasoft/api/MyVintasoftBarcodeApi");
// create the barcode writer
var barcodeWriter = new Vintasoft.Barcode.WebBarcodeWriterJS(barcodeService);
// create the barcode writer settings for generating 2D barcode
var barcodeWriterSettings = 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(__writeBarcode_success, __writeBarcode_failed);
}
catch (ex) {
alert("Error: " + ex);
}
}
/**
* Generates 2D barcode image.
* @param barcodeType Barcode type.
* @param barcodeValue Barcode value.
*/
function __generate2dBarcodeImage(barcodeType, barcodeValue) {
try {
// declare reference to the Vintasoft namespace
var Vintasoft = window.Vintasoft;
if (Vintasoft.Shared.WebImagingEnviromentJS.get_SessionId() == null)
// set the session identifier
Vintasoft.Shared.WebImagingEnviromentJS.set_SessionId("SessionID");
// create web service that allows to generate barcode
var barcodeService = new Vintasoft.Shared.WebServiceControllerJS("vintasoft/api/MyVintasoftBarcodeApi");
// create the barcode writer
var barcodeWriter = new Vintasoft.Barcode.WebBarcodeWriterJS(barcodeService);
// create the barcode writer settings for generating 2D barcode
var barcodeWriterSettings = 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(__writeBarcode_success, __writeBarcode_failed);
}
catch (ex) {
alert("Error: " + ex);
}
}
/**
* Barcode is generated successfully.
* @param data Object that stores response from barcode service.
*/
function __writeBarcode_success(data) {
if (data.success) {
var barcodeImage = data.barcodeImage;
var barcodeImageElement = document.getElementById("barcodeImage");
barcodeImageElement.src = barcodeImage;
}
else {
alert(data.errorMessage);
}
}
/**
* Barcode generation is failed.
* @param data Object with information about error.
*/
function __writeBarcode_failed(data) {
// show information about error
alert(data.errorMessage);
}
export default App
-
Откройте файл "Properties\launchSettings.json" в проекте "ReactApp1.Server" и получите URL веб-сервиса из параметра "applicationUrl" раздела "profiles\https" - в этом примере URL - "https://localhost:7109":
Откройте файл "vite.config.js" в проекте "reactapp1.client" и укажите, что приложение React.js может иметь доступ к веб-сервису в проекте "ReactApp1.Server" (добавьте раздел "server" в объект "defineConfig"):
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
const target = 'https://localhost:7109';
// https://vite.dev/config/
export default defineConfig({
plugins: [react()],
server: {
proxy: {
'^/vintasoft/api/': {
target,
secure: false
}
},
port: 7109
}
})
-
Запустите приложение "React.js with ASP.NET Core" и посмотрите результат.