VintaSoft Imaging .NET SDK 14.0: Документация для Веб разработчика
В этом разделе
    Добавление веб редактора PDF документа в приложения React и Приложение ASP.NET Core
    В этом разделе
    В этом руководстве показано, как создать пустое приложение React и ASP.NET Core в Visual Studio .NET 2022 и добавить редактор PDF документа в приложение React и ASP.NET Core.

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

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

      • Настройте приложение для использования .NET 8.0:
    2. Серверная часть: Добавьте ссылки на .NET-сборки Vintasoft в проект "ReactApp1.Server".

      Скопируйте сборки Vintasoft.Shared.dll, Vintasoft.Imaging.dll, Vintasoft.Imaging.Pdf.dll, Vintasoft.Shared.Web.dll, Vintasoft.Imaging.Web.Services.dll, Vintasoft.Imaging.Pdf.Web.Services.dll, Vintasoft.Imaging.AspNetCore.ApiControllers.dll и Vintasoft.Imaging.Pdf.AspNetCore.ApiControllers.dll из каталога "\VintaSoft Imaging .NET 14.0\Bin\DotNet8\AnyCPU\" в каталог "Bin" проекта "ReactApp1.Server" и добавьте ссылки на сборки в проекте "ReactApp1.Server".



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

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

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

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

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

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

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

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

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

          Вот исходные коды класса MyVintasoftImageCollectionApiController:
          namespace ReactApp1.Server.Controllers
          {
              public class MyVintasoftImageCollectionApiController : Vintasoft.Imaging.AspNetCore.ApiControllers.VintasoftImageCollectionApiController
              {
          
                  public MyVintasoftImageCollectionApiController(IWebHostEnvironment hostingEnvironment)
                      : base(hostingEnvironment)
                  {
                  }
          
              }
          }
          
          
      • Создайте веб сервис, который позволяет получать информацию об изображениях, получать миниатюры, рендерить тайлы изображений, извлекать/искать текст

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

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

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

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

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

        Вот исходные коды файла "Program.cs" после обновления:
        Vintasoft.Imaging.Drawing.SkiaSharp.SkiaSharpDrawingFactory.SetAsDefault();
        
        var builder = WebApplication.CreateBuilder(args);
        
        // Add services to the container.
        
        builder.Services.AddControllers();
        builder.Services.AddControllersWithViews();
        
        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" в "ReactApp1.Server" и очистите стартовый URL-адрес приложения:
    7. Сторона сервера: Скопируйте тестовый PDF документ по умолчанию на сторону сервера.

      • Создайте папку "UploadedImageFiles\SessionID" в проекте "ReactApp1.Server" и скопируйте в нее тестовый PDF документ "\VintaSoft\Imaging .NET 14.0\Examples\ASP.NET Core\CSharp\AspNetCoreImagingDemo\wwwroot\UploadedImageFiles\VintasoftImagingDemo.pdf". Этот документ будет отображен в редакторе PDF документов.
    8. Скомпилируйте проект для восстановления зависимостей с помощью 'npm'

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

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

      • Удалите файлы "src\App.css" и "src\App.jsx" - этот React-компонент не требуется в этом руководстве.
    10. Клиентская сторона: Добавьте JavaScript-файлы в проект "reactapp1.client".

      • Скопируйте файлы Vintasoft.Shared.js, Vintasoft.Imaging.js и Vintasoft.Imaging.Pdf.js из папки "\VintaSoft Imaging .NET 14.0\Bin\JavaScript\" в папку "public\".

      • Укажите, какие "стандартные" UI-диалоги (диалог ввода пароля, диалог печати и т. д.) должны использоваться веб редактором PDF документа
        • Если веб редактор PDF документа должен использовать готовые к использованию "стандартные" UI-диалоги Bootstrap:
          • Добавьте Node-модуль "bootstrap" в файл "package.json". Пересоберите проект для обновления Node-модулей.
            Вот исходные коды файла "package.json" после обновления:
            {
              "name": "reactapp1.client",
              "private": true,
              "version": "0.0.0",
              "type": "module",
              "scripts": {
                "dev": "vite",
                "build": "vite build",
                "lint": "eslint . --ext js,jsx --report-unused-disable-directives --max-warnings 0",
                "preview": "vite preview"
              },
              "dependencies": {
                "react": "^18.2.0",
                "react-dom": "^18.2.0",
                "bootstrap": "5.3.3"
              },
              "devDependencies": {
                "@types/react": "^18.2.66",
                "@types/react-dom": "^18.2.22",
                "@vitejs/plugin-react": "^4.2.1",
                "eslint": "^8.57.0",
                "eslint-plugin-react": "^7.34.1",
                "eslint-plugin-react-hooks": "^4.6.0",
                "eslint-plugin-react-refresh": "^0.4.6",
                "vite": "^5.2.0"
              }
            }
            
            
          • Скопируйте файлы Vintasoft.Imaging.Dialogs.Bootstrap.js и Vintasoft.Imaging.Pdf.Dialogs.Bootstrap.js из папки "\VintaSoft Imaging .NET 14.0\Bin\JavaScript\" в папку "public\".

        • Если веб редактор PDF документа должен использовать готовые к использованию "стандартные" UI-диалоги jQuery UI:
          • Добавьте Node-модуль "jquery-ui-dist" в файл "package.json". Пересоберите проект для обновления Node-модулей.
          • Скопируйте файлы Vintasoft.Imaging.Dialogs.jQueryUI.js и Vintasoft.Imaging.Pdf.Dialogs.jQueryUI.js из папки "\VintaSoft Imaging .NET 14.0\Bin\JavaScript\" в папку "src\app\assets\".

        • Если веб редактор PDF документа должен использовать пользовательские "стандартные" UI-диалоги, прочтите, как создать пользовательские "стандартные" UI-диалоги здесь .

      • Скопируйте файлы Vintasoft.Imaging.css и Vintasoft.Imaging.Pdf.css с CSS-стилями редактора веб-PDF документов Vintasoft из папки "\VintaSoft\Imaging .NET 14.0\Bin\JavaScript\" в папку "public\".

      • Добавьте ссылки на Bootstrap CSS-файл и Vintasoft CSS-файлы в файл "index.html", добавбте ссылки на Vintasoft JavaScript-файлы в заголовок файла "index.html":


        Вот исходные коды файла "index.html":
        <!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>Vite + React</title>
        
            <link rel="stylesheet" type="text/css" href="node_modules\bootstrap\dist\css\bootstrap.css" />
            <link rel="stylesheet" type="text/css" href="public/Vintasoft.Imaging.css">
            <link rel="stylesheet" type="text/css" href="public/Vintasoft.Imaging.Pdf.css">
            <link rel="stylesheet" type="text/css" href="src/PdfDocumentEditorDemo.css">
        
            <script src="public/Vintasoft.Shared.js" type="text/javascript"></script>
            <script src="public/Vintasoft.Imaging.js" type="text/javascript"></script>
            <script src="public/Vintasoft.Imaging.Dialogs.Bootstrap.js" type="text/javascript"></script>
            <script src="public/Vintasoft.Imaging.Pdf.js" type="text/javascript"></script>
            <script src="public/Vintasoft.Imaging.Pdf.Dialogs.Bootstrap.js" type="text/javascript"></script>
        </head>
          <body>
            <div id="root"></div>
            <script type="module" src="/src/main.jsx"></script>
          </body>
        </html>
        
        

      • Добавьте CSS-стиль "pdfDocumentEditorContainer", который определяет размер контейнера редактора PDF документов, в файл "src\PdfDocumentEditorDemo.css":


        Вот исходные коды файла "PdfDocumentEditorDemo.css":
        h1 {
            width: 1200px;
            text-align: center;
        }
        
        .pdfDocumentEditorContainer {
            width: 1200px;
            height: 800px;
        }
        
        
    11. Клиентская сторона: Создайте React-компонент, позволяющий просматривать, печатать, редактировать, проверять, конвертировать, сохранять PDF документ.

      • Создайте файл "PdfDocumentEditorDemo.jsx", который будет содержать исходные коды React-компонента (класс PdfDocumentEditorDemo):
        • Выберите контекстное меню "Add => New Item..." для папкb "src\" => Появится UI-диалог "Add new item"
        • Выберите тип "JSX-файл" для нового элемента
        • Установите "PdfDocumentEditorDemo.jsx" в качестве имени элемента
        • Нажмите кнопку "Добавить" => диалоговое окно будет закрыто, а файл "PdfDocumentEditorDemo.jsx" будет добавлен в папку "src\"

        Добавьте объявление класса PdfDocumentEditorDemo с функцией 'render' (отображает заголовок приложения и div-элемент, который будет отображать редактор PDF документа) в файл "PdfDocumentEditorDemo.jsx":


        Добавьте функцию 'componentDidMount' (содержит код JavaScript, который инициализирует и создает редактор PDF документа) для класса PdfDocumentEditorDemo:


        Важно: Visual Studio использует случайный сетевой порт для ASP.NET Core API, и вам необходимо обновить JavaScript-код и изменить URL-адрес веб-службы с "https://localhost:7240/" на URL-адрес в вашем приложение.

        Вот код JavaScript файла "PdfDocumentEditorDemo.jsx":
        import { Component } from 'react';
        
        export class PdfDocumentEditorDemo extends Component {
            static displayName = PdfDocumentEditorDemo.name;
            static _isInitialized = false;
        
            render() {
                return (
                    <div>
                        <h1>VintaSoft PDF Document Editor Demo (ASP.NET Core + React.js)</h1>
        
                        <div id="pdfDocumentEditorContainer" className="pdfDocumentEditorContainer"></div>
                    </div>
                );
            }
        
            componentDidMount() {
                if (this._isInitialized)
                    return;
                this._isInitialized = true;
        
                // declare reference to the Vintasoft namespace
                let Vintasoft = window.Vintasoft;
        
                // set the session identifier
                Vintasoft.Shared.WebImagingEnviromentJS.set_SessionId("SessionID");
        
                // specify web services, which should be used by Vintasoft Web PDF Document Editor
                Vintasoft.Shared.WebServiceJS.defaultFileService =
                    new Vintasoft.Shared.WebServiceControllerJS("https://localhost:7240/vintasoft/api/MyVintasoftFileApi");
                Vintasoft.Shared.WebServiceJS.defaultImageCollectionService =
                    new Vintasoft.Shared.WebServiceControllerJS("https://localhost:7240/vintasoft/api/MyVintasoftImageCollectionApi");
                Vintasoft.Shared.WebServiceJS.defaultImageService =
                    new Vintasoft.Shared.WebServiceControllerJS("https://localhost:7240/vintasoft/api/MyVintasoftImageApi");
                Vintasoft.Shared.WebServiceJS.defaultPdfService =
                    new Vintasoft.Shared.WebServiceControllerJS("https://localhost:7240/vintasoft/api/MyVintasoftPdfApi");
        
                // create settings for PDF document editor
                let pdfDocumentEditorSettings =
                    new Vintasoft.Imaging.Pdf.UI.WebPdfDocumentEditorControlSettingsJS("pdfDocumentEditorContainer");
        
                // create the PDF document editor
                let pdfDocumentEditor = new Vintasoft.Imaging.Pdf.UI.WebPdfDocumentEditorControlJS(pdfDocumentEditorSettings);
        
                // get thumbnail viewer of PDF document editor
                let thumbnailViewer = pdfDocumentEditor.get_ThumbnailViewer();
                // specify that thumbnail viewer should not cache thumbnails on server side
                thumbnailViewer.set_UseCache(false);
        
                // get image viewer of PDF document editor
                let imageViewer = pdfDocumentEditor.get_ImageViewer();
                // specify that image viewer should not cache image tiles on server side
                imageViewer.set_UseCache(false);
                // open file from session folder and add images from file to the image viewer
                imageViewer.get_Images().openFile("VintasoftImagingDemo.pdf");
            }
        
        }
        

      • Добавьте созданный React-компонент в код React-приложения - файл "src\main.jsx":


        Вот исходные коды файла "main.jsx" после обновления:
        import React from 'react'
        import ReactDOM from 'react-dom/client'
        import { PdfDocumentEditorDemo } from './PdfDocumentEditorDemo.jsx'
        import './index.css'
        
        ReactDOM.createRoot(document.getElementById('root')).render(
            <React.StrictMode>
                <PdfDocumentEditorDemo />
            </React.StrictMode>,
        )
        
        
    12. Запустите "React + ASP.NET Core" приложение и посмотрите результат.