VintaSoft Imaging .NET SDK 14.1: Документация для Веб разработчика
В этом разделе
    Добавление веб редактора электронных таблиц в "Angular + ASP.NET Core" приложение
    В этом разделе
    В этом руководстве показано, как создать пустое "Angular + ASP.NET Core" приложение в Visual Studio .NET 2022 и добавить веб редактор электронных таблиц (с возможностью открытия, редактирования и сохранения электронных таблиц (XLSX)) в "Angular + ASP.NET Core" приложение.

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

      Откройте Visual Studio .NET 2022 и создайте новое приложение типа "Angular + ASP.NET Core":

      Настройте приложение для использования .NET 8.0:

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

      Скопируйте файлы Vintasoft.Shared.dll, Vintasoft.Imaging.dll, Vintasoft.Imaging.Office.OpenXml.dll, Vintasoft.Shared.Web.dll, Vintasoft.Imaging.Web.Services.dll, Vintasoft.Imaging.Office.Web.Services.dll, Vintasoft.Imaging.AspNetCore.ApiControllers.dll и Vintasoft.Imaging.Office.AspNetCore.ApiControllers.dll из папки "<SdkInstallPath>\VintaSoft Imaging .NET 14.1\Bin\DotNet8\AnyCPU\" в папку "Bin" проекта "AngularApp1.Server" и добавьте ссылки на .NET-сборки в проект "AngularApp1.Server".



    3. Серверная сторона: Укажите движок рисования, который должен использоваться VintaSoft Imaging .NET SDK для рисования 2D-графики.

      Если проект "AngularApp1.Server" необходимо использовать в Windows или Linux, следует использовать движок рисования SkiaSharp.
      Если проект "AngularApp1.Server" необходимо использовать только в Windows, следует использовать движок рисования System.Drawing или SkiaSharp.

      Вот шаги, которые необходимо выполнить для использования движка SkiaSharp:
      • Добавьте ссылку на .NET-сборку Vintasoft.Imaging.Drawing.SkiaSharp.dll.
      • Добавьте ссылку на nuget-пакет SkiaSharp версии 3.116.1.
      • Откройте файл "Program.cs" в проекте "AngularApp1.Server", добавьте строку кода "Vintasoft.Imaging.Drawing.SkiaSharp.SkiaSharpDrawingFactory.SetAsDefault();" в начало файла - добавленный код указывает, что VintaSoft Imaging .NET SDK должен использовать библиотеку SkiaSharp для рисования 2D-графики.

      Вот шаги, которые необходимо выполнить для использования движка System.Drawing:
      • Добавьте ссылку на .NET-сборку Vintasoft.Imaging.Gdi.dll.
      • Откройте файл "Program.cs" в проекте "AngularApp1.Server", добавьте строку кода "Vintasoft.Imaging.Drawing.Gdi.GdiGraphicsFactory.SetAsDefault();" в начало файла - добавленный код указывет, что VintaSoft Imaging .NET SDK должен использовать библиотеку System.Drawing для рисования 2D-графики.

    4. Серверная сторона: Создайте веб сервисы, позволяющие загружать/скачивать файлы и редактировать документы XLSX.

      • Добавьте в проект папку "Controllers".
      • Создайте веб сервис, позволяющий загружать/скачивать файл

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

          Вот исходные коды класса MyVintasoftFileApiController:
          namespace AngularApp1.Server.Controllers
          {
              public class MyVintasoftFileApiController : Vintasoft.Imaging.AspNetCore.ApiControllers.VintasoftFileApiController
              {
          
                  public MyVintasoftFileApiController(IWebHostEnvironment hostingEnvironment)
                      : base(hostingEnvironment)
                  {
                  }
          
              }
          }
          
          
      • Создать веб сервис, позволяющий редактировать XLSX документ.

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

          Вот исходные коды класса MyVintasoftOfficeApiController:
          namespace AngularApp1.Server.Controllers
          {
              public class MyVintasoftOfficeApiController : Vintasoft.Imaging.Office.AspNetCore.ApiControllers.VintasoftOfficeApiController
              {
                  public MyVintasoftOfficeApiController(IWebHostEnvironment hostingEnvironment)
                      : base(hostingEnvironment)
                  {
                  }
              }
          }
          
          
    5. Серверная сторона: Создайте CORS-политику, позволяющую получать доступ к веб сервисам из клиентского приложения.

      • Откройте файл "Program.cs" в проекте "AngularApp1.Server" и добавьте код, который:
        • Создает CORS-политику, которая позволяет получать доступ к веб сервисам с веб сервера "localhost"
        • Включает использование CORS в проекте "AngularApp1.Server"

        Вот исходные коды файла "Program.cs" после обновления:
        Vintasoft.Imaging.Drawing.SkiaSharp.SkiaSharpDrawingFactory.SetAsDefault();
        
        var builder = WebApplication.CreateBuilder(args);
        
        // Add services to the container.
        
        builder.Services.AddControllers();
        
        builder.Services.AddCors(options =>
        {
            options.AddPolicy(name: "CorsPolicy1", policy =>
            {
                policy.SetIsOriginAllowed(origin => new Uri(origin).Host == "localhost").AllowAnyHeader().AllowAnyMethod();
            });
        });
        
        var app = builder.Build();
        
        app.UseDefaultFiles();
        app.UseStaticFiles();
        
        // Configure the HTTP request pipeline.
        
        app.UseHttpsRedirection();
        
        app.UseAuthorization();
        
        app.UseCors("CorsPolicy1");
        
        app.MapControllers();
        
        app.MapFallbackToFile("/index.html");
        
        app.Run();
        
        
    6. Серверная сторона: Обновите стартовый URL-адрес приложения в файле "launchSettings.json".

      • Откройте файл "Properties\launchSettings.json" в "AngularApp1.Server" и очистите стартовый URL-адрес приложения:
    7. Серверная сторона: Скопируйте тестовый XLSX документ по умолчанию на сервер.

      • Создайте папку "UploadedImageFiles\SessionID" в проекте "AngularApp1.Server" и скопируйте тестовый XLSX документ "<SdkInstallPath>\VintaSoft\Imaging .NET 14.1\Examples\ASP.NET Core\CSharp\AspNetCoreSpreadsheetEditorDemo\wwwroot\UploadedImageFiles\SalesReport.xlsx" в папку "UploadedImageFiles\SessionID". Этот документ будет отображен в веб редакторе электронных таблиц.

      • Создайте папку "Resources" в проекте "AngularApp1.Server" и скопируйте XLSX документ "<SdkInstallPath>\VintaSoft\Imaging .NET 14.1\Examples\ASP.NET Core\CSharp\AspNetCoreSpreadsheetEditorDemo\wwwroot\Resources\ChartSource.xlsx" в папку "Resources". Этот документ будет использоваться в качестве источника для "стандартных" диаграмм при добавлении диаграммы в документ электронных таблиц с помощью UI-диалога "Add chart".
    8. Скомпилируйте проект для восстановления зависимостей с помощью 'npm'

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

      • Удалите файлы "WeatherForecast.cs" и "Controllers\WeatherForecastController.cs" в проекте "AngularApp1.Server" - ASP.NET Core Web API контроллер WeatherForecast не требуется в этом руководстве.

      • Удалить файлы "src\app\app.comComponent.css", "src\app\app.comComponent.html", "src\app\app.comComponent.spec.ts", "src \app\app.comComponent.ts" в проекте "angularapp1.client" - этот Angular-компонент не требуется в этом руководстве.
    10. Клиентская сторона: Добавьте JavaScript-файлы и TypeScript-модули в проект "angularapp1.client".

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

      • Скопируйте файлы Vintasoft.Shared.js, Vintasoft.Shared.d.ts, Vintasoft.Imaging.js, Vintasoft.Imaging.d.ts, Vintasoft.Imaging.Office.js и Vintasoft.Imaging.Office.d.ts из папки "<SdkInstallPath>\VintaSoft Imaging .NET 14.1\Bin\JavaScript" в папку "src\app\assets\".

      • Укажите, какие "стандартные" UI-диалоги (UI-диалог переименования рабочего листа, UI-диалог поиска текста и т. д.) должны использоваться веб редактором электронных таблиц.
        • Если веб редактор электронных таблиц должен использовать готовые к использованию "стандартные" UI-диалоги Bootstrap:
          • Добавьте Node-модуль "bootstrap" в файл "package.json". Пересоберите проект для обновления Node-модулей.
            Вот исходные коды файла "package.json" после обновления:
            {
              "name": "angularapp1.client",
              "version": "0.0.0",
              "scripts": {
                "ng": "ng",
                "start": "run-script-os",
                "build": "ng build",
                "watch": "ng build --watch --configuration development",
                "test": "ng test",
                "prestart": "node aspnetcore-https",
                "start:windows": "ng serve --ssl --ssl-cert \"%APPDATA%\\ASP.NET\\https\\%npm_package_name%.pem\" --ssl-key \"%APPDATA%\\ASP.NET\\https\\%npm_package_name%.key\" --host=127.0.0.1",
                "start:default": "ng serve --ssl --ssl-cert \"$HOME/.aspnet/https/${npm_package_name}.pem\" --ssl-key \"$HOME/.aspnet/https/${npm_package_name}.key\" --host=127.0.0.1"
              },
              "private": true,
              "dependencies": {
                "@angular/animations": "^18.0.0",
                "@angular/common": "^18.0.0",
                "@angular/compiler": "^18.0.0",
                "@angular/core": "^18.0.0",
                "@angular/forms": "^18.0.0",
                "@angular/platform-browser": "^18.0.0",
                "@angular/platform-browser-dynamic": "^18.0.0",
                "@angular/router": "^18.0.0",
                "bootstrap": "5.3.3",
                "rxjs": "~7.8.0",
                "tslib": "^2.3.0",
                "zone.js": "~0.14.3",
                "jest-editor-support": "*",
                "run-script-os": "*"
              },
              "devDependencies": {
                "@angular-devkit/build-angular": "^18.0.3",
                "@angular/cli": "^18.0.3",
                "@angular/compiler-cli": "^18.0.0",
                "@types/jasmine": "~5.1.0",
                "jasmine-core": "~5.1.0",
                "karma": "~6.4.0",
                "karma-chrome-launcher": "~3.2.0",
                "karma-coverage": "~2.2.0",
                "karma-jasmine": "~5.1.0",
                "karma-jasmine-html-reporter": "~2.1.0",
                "typescript": "~5.4.2"
              }
            }
            
            
          • Скопируйте файлы Vintasoft.Imaging.Dialogs.Bootstrap.js, Vintasoft.Imaging.Dialogs.Bootstrap.d.ts, Vintasoft.Imaging.Office.Dialogs.Bootstrap.js и Vintasoft.Imaging.Office.Dialogs.Bootstrap.d.ts из папки "<SdkInstallPath>\VintaSoft Imaging .NET 14.1\Bin\JavaScript\" в папку "src\app\assets\".

        • Если веб редактор электронных таблиц должен использовать готовые к использованию "стандартные" UI-диалоги jQuery UI:
          • Добавьте Node-модуль "jquery-ui-dist" в файл "package.json". Пересоберите проект для обновления Node-модулей.
          • Скопируйте файлы Vintasoft.Imaging.Dialogs.jQueryUI.js, Vintasoft.Imaging.Dialogs.jQueryUI.d.ts, Vintasoft.Imaging.Office.Dialogs.jQueryUI.js и Vintasoft.Imaging.Office.Dialogs.jQueryUI.d.ts из папки "<SdkInstallPath>\VintaSoft Imaging .NET 14.1\Bin\JavaScript\" в папку "src\app\assets\".

        • Если веб редактор электронных таблиц должен использовать пользовательские "стандартные" UI-диалоги (например, UI-диалоги Angular+Bootstrap), прочтите, как создавать пользовательские "стандартные" UI-диалоги здесь .

      • Добавьте ссылки на используемые JavaScript-библиотеки в секцию "projects => Demo => architect => build => options => scripts" в файле "angular.json", добавьте ссылки на используемые CSS-файлы в секцию "projects => Demo => architect => build => options => styles" в файле "angular.json".
        Вот исходные коды файла "angular.json":
        {
          "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
          "version": 1,
          "newProjectRoot": "projects",
          "projects": {
            "angularapp1.client": {
              "projectType": "application",
              "schematics": {
                "@schematics/angular:component": {
                  "standalone": false
                },
                "@schematics/angular:directive": {
                  "standalone": false
                },
                "@schematics/angular:pipe": {
                  "standalone": false
                }
              },
              "root": "",
              "sourceRoot": "src",
              "prefix": "app",
              "architect": {
                "build": {
                  "builder": "@angular-devkit/build-angular:application",
                  "options": {
                    "outputPath": "dist/angularapp1.client",
                    "index": "src/index.html",
                    "browser": "src/main.ts",
                    "polyfills": [
                      "zone.js"
                    ],
                    "tsConfig": "tsconfig.app.json",
                    "assets": [
                      {
                        "glob": "**/*",
                        "input": "public"
                      }
                    ],
                    "styles": [
                      "node_modules/bootstrap/dist/css/bootstrap.min.css",
                      "src/styles.css",
                      "src/Vintasoft.Imaging.css",
                      "src/Vintasoft.Imaging.Office.css"
                    ],
                    "scripts": [
                      "src/app/assets/Vintasoft.Shared.js",
                      "src/app/assets/Vintasoft.Imaging.js",
                      "src/app/assets/Vintasoft.Imaging.Dialogs.Bootstrap.js",
                      "src/app/assets/Vintasoft.Imaging.Office.js",
                      "src/app/assets/Vintasoft.Imaging.Office.Dialogs.Bootstrap.js"
                    ]
                  },
                  "configurations": {
                    "production": {
                      "budgets": [
                        {
                          "type": "initial",
                          "maximumWarning": "500kB",
                          "maximumError": "1MB"
                        },
                        {
                          "type": "anyComponentStyle",
                          "maximumWarning": "2kB",
                          "maximumError": "4kB"
                        }
                      ],
                      "outputHashing": "all"
                    },
                    "development": {
                      "optimization": false,
                      "extractLicenses": false,
                      "sourceMap": true
                    }
                  },
                  "defaultConfiguration": "production"
                },
                "serve": {
                  "builder": "@angular-devkit/build-angular:dev-server",
                  "configurations": {
                    "production": {
                      "buildTarget": "angularapp1.client:build:production"
                    },
                    "development": {
                      "buildTarget": "angularapp1.client:build:development"
                    }
                  },
                  "defaultConfiguration": "development",
                  "options": {
                    "proxyConfig": "src/proxy.conf.js"
                  }
                },
                "extract-i18n": {
                  "builder": "@angular-devkit/build-angular:extract-i18n"
                },
                "test": {
                  "builder": "@angular-devkit/build-angular:karma",
                  "options": {
                    "polyfills": [
                      "zone.js",
                      "zone.js/testing"
                    ],
                    "tsConfig": "tsconfig.spec.json",
                    "assets": [
                      {
                        "glob": "**/*",
                        "input": "public"
                      }
                    ],
                    "styles": [
                      "src/styles.css"
                    ],
                    "scripts": [],
                    "karmaConfig": "karma.conf.js"
                  }
                }
              }
            }
          }
        }
        
        

      • Скопируйте файлы "Vintasoft.Imaging.css" и "Vintasoft.Imaging.Office.css" с CSS-стилями веб редактора электронных таблиц из папки "<SdkInstallPath>\VintaSoft\Imaging .NET 14.1\Bin\JavaScript\" в папку "src".
        Добавьте информацию о файлах Vintasoft.Imaging.css и Vintasoft.Imaging.Office.css в секцию "styles" файла "app\angular.json".
    11. Клиентская сторона: Создайте Angular-компонент, который позволяет отображать и редактировать документ электронных таблиц.

      • Создайте файл "spreadsheet-document-editor-demo.html", который будет содержать HTML-разметку Angular-компонента:
        • Выберите контекстное меню "Add => New Item..." для папки "src\app\" => Появится UI-диалог "Add new item"
        • Выберите тип "HTML Page" для нового элемента
        • Установите "spreadsheet-document-editor-demo.html" в качестве имени элемента
        • Нажмите кнопку "Add" => UI-диалог закроется и файл "spreadsheet-document-editor-demo.html" будет добавлен в папку "src\app\"

        Добавьте HTML-разметку (заголовок приложения и div-элемент для веб редактора электронных таблиц) в файл "spreadsheet-document-editor-demo.html":


        Вот HTML-код файла "spreadsheet-document-editor-demo.html":
        <h1>VintaSoft Spreadsheet Document Editor (Angular + ASP.NET Core)</h1>
        
        <div id="spreadsheetDocumentEditorContainer" class="spreadsheetDocumentEditorContainer"></div>
        
        

      • Создать файл "spreadsheet-document-editor-demo.css", который будет содержать CSS-стили Angular-компонента:
        • Выберите контекстное меню "Add => New Item..." для папки "src\app\" => Появится UI-диалог "Add new item"
        • Выберите тип "StyleSheet" для нового элемента
        • Установите "spreadsheet-document-editor-demo.css" в качестве имени элемента
        • Нажмите кнопку "Add" => UI-диалог закроется и файл "spreadsheet-document-editor-demo.css" будет добавлен в папку "src\app\"

        Добавьте CSS-стили в файл "spreadsheet-document-editor-demo.css":


        Вот CSS-код файла "spreadsheet-document-editor-demo.css":
        h1 {
          text-align: center;
        }
        
        .spreadsheetDocumentEditorContainer {
          height: 800px;
        }
        
        

      • Создайте файл "spreadsheet-document-editor-demo.ts", который будет содержать код Angular-компонента:
        • Выберите контекстное меню "Add => New Item..." для папки "src\app\" => Появится UI-диалог "Add new item"
        • Выберите тип "TypeScript File" для нового элемента
        • Установить "spreadsheet-document-editor-demo.ts" в качестве имени элемента
        • Нажмите кнопку "Add" => UI-диалог закроется и файл "spreadsheet-document-editor-demo.ts" будет добавлен в папку "src\app\"

        Добавьте TypeScript-код в файл "spreadsheet-document-editor-demo.ts":


        Вот TypeScript-код файла "spreadsheet-document-editor-demo.ts":
        import { Component, OnInit } from '@angular/core';
        
        @Component({
          selector: 'app-root',
          templateUrl: './spreadsheet-document-editor-demo.html',
          styleUrl: './spreadsheet-document-editor-demo.css'
        })
        export class SpreadsheetDocumentEditorDemo implements OnInit {
          constructor() { }
        
          ngOnInit() {
            // set the session identifier
            Vintasoft.Shared.WebImagingEnviromentJS.set_SessionId("SessionId");
        
            // specify web services, which should be used in this demo
            Vintasoft.Shared.WebServiceJS.defaultFileService = new Vintasoft.Shared.WebServiceControllerJS("https://localhost:7015/vintasoft/api/MyVintasoftFileApi");
            Vintasoft.Shared.WebServiceJS.defaultOfficeService = new Vintasoft.Shared.WebServiceControllerJS("https://localhost:7015/vintasoft/api/MyVintasoftOfficeApi");
        
            // create the spreadsheet document editor control settings
            var spreadsheetDocumentEditorControlSettings = new Vintasoft.Imaging.Office.UI.WebSpreadsheetDocumentEditorControlSettingsJS("spreadsheetDocumentEditorContainer", "");
        
            // create the spreadsheet document editor control
            var spreadsheetDocumentEditorControl = new Vintasoft.Imaging.Office.UI.WebSpreadsheetDocumentEditorControlJS(spreadsheetDocumentEditorControlSettings);
        
            // subscribe to the "warningOccured" event of spreadsheet document editor control
            Vintasoft.Shared.subscribeToEvent(spreadsheetDocumentEditorControl, "warningOccured", this.__spreadsheetDocumentEditorControl_warningOccured);
        
            var fileId = "SalesReport.xlsx";
            // copy the file from global folder to the session folder
            spreadsheetDocumentEditorControl.openDocument(fileId);
          }
        
          __spreadsheetDocumentEditorControl_warningOccured(event: any, eventArgs: any) {
            // show the error message
            alert(eventArgs.message);
          }
        
          title = 'VintaSoft Angular Spreadsheet Document Editor Demo';
        }
        
        

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


        Вот исходные коды файла "app.module.ts" после обновления:
        import { HttpClientModule } from '@angular/common/http';
        import { NgModule } from '@angular/core';
        import { BrowserModule } from '@angular/platform-browser';
        
        import { AppRoutingModule } from './app-routing.module';
        import { SpreadsheetDocumentEditorDemo } from './spreadsheet-document-editor-demo';
        
        @NgModule({
          declarations: [
            SpreadsheetDocumentEditorDemo
          ],
          imports: [
            BrowserModule, HttpClientModule,
            AppRoutingModule
          ],
          providers: [],
          bootstrap: [SpreadsheetDocumentEditorDemo]
        })
        export class AppModule { }
        
        

    12. Запустите "Angular + ASP.NET Core" приложение и посмотрите результат.