VintaSoft Imaging .NET SDK 15.0: Документация для Веб разработчика
В этом разделе
    Добавление веб просмотрщика документов в приложение "Vue и ASP.NET Core"
    В этом разделе
    В этом руководстве показано, как создать пустое приложение "Vue и ASP.NET Core" в Visual Studio .NET 2026 и добавить в него веб просмотрщик документов (с возможностью открытия изображений и документов (PDF, DOCX, XLSX), извлечения/поиска текста, аннотирования документов).

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

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

      • Настройте приложение для использования .NET 10.0:
    2. Проект "VueApp1.Server": Добавьте ссылки на nuget-пакеты Vintasoft в проект "VueApp1.Server".

      Добавьте ссылки на nuget-пакеты "Vintasoft.Imaging.Annotation.AspNetCore.ApiControllers", "Vintasoft.Imaging.Annotation.Pdf" и "Vintasoft.Imaging.Office.OpenXml" в проект "VueApp1.Server". Другие необходимые nuget-пакеты будут добавлены автоматически.



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

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

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

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

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

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

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

          Вот исходные коды класса MyVintasoftFileApiController:
          namespace VueApp1.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 VueApp1.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 VueApp1.Server.Controllers
          {
              public class MyVintasoftImageApiController : Vintasoft.Imaging.AspNetCore.ApiControllers.VintasoftImageApiController
              {
          
                  public MyVintasoftImageApiController(IWebHostEnvironment hostingEnvironment)
                      : base(hostingEnvironment)
                  {
                  }
          
              }
          }
          
      • Создайте веб сервис, который позволяет комментировать изображения и документы

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

          Вот исходные коды класса MyVintasoftAnnotationCollectionApiController:
          namespace VueApp1.Server.Controllers
          {
              public class MyVintasoftAnnotationCollectionApiController :
                  Vintasoft.Imaging.Annotation.AspNetCore.ApiControllers.VintasoftAnnotationCollectionApiController
              {
          
                  public MyVintasoftAnnotationCollectionApiController(IWebHostEnvironment hostingEnvironment)
                      : base(hostingEnvironment)
                  {
                  }
              }
          }
          
    5. Проект "VueApp1.Server": Добавьте Newtonsoft JSON для десериализации JSON-аннотаций.

      • Добавьте ссылку на nuget-пакет Microsoft.AspNetCore.Mvc.NewtonsoftJson.
      • Откройте файл "Program.cs" в проекте "VueApp1.Server" и добавьте строку кода "builder.Services.AddControllersWithViews().AddNewtonsoftJson();" после строки "builder.Services.AddControllers();". Это необходимо для корректной десериализации JSON-аннотаций.

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

      • Создайте папку "UploadedImageFiles\SessionID" в проекте "VueApp1.Server" и скопируйте тестовый PDF документ "<SdkInstallPath>\VintaSoft\Imaging .NET 15.0\Examples\ASP.NET Core\CSharp\AspNetCoreImagingDemo\wwwroot\UploadedImageFiles\VintasoftImagingDemo.pdf" в папку. Этот документ будет отображен в веб просмотрщике документов.
    7. Удалите файлы, которые не нужны в этом руководстве.

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

      • Удалите файлы "src\components\TheWelcome.vue", "src\components\WelcomeItem.vue" в проекте "vueapp1.client" - этот Vue-компонент не требуется в этом руководстве.

      • Откройте файл "src\App.vue" в проекте "vueapp1.client" и удалите код, который использует следующие Vue-компоненты: HelloWorld, TheWelcome - эти Vue-компоненты не нужны в этом руководстве.
        Вот исходные коды файла "App.vue" после обновления:
        <script setup>
        </script>
        
        <template>
            <main>
            </main>
        </template>
        
        <style scoped>
        </style>
        
        
    8. Скомпилируйте решение для восстановления зависимостей TypeScript в проекте "vueapp1.client".

    9. Проект "vueapp1.client": Добавьте файлы JavaScript в проект "vueapp1.client".

      • Скопируйте файлы Vintasoft.Shared.js, Vintasoft.Imaging.js, Vintasoft.Imaging.Annotation.js и Vintasoft.Imaging.DocumentViewer.js из папки "<SdkInstallPath>\VintaSoft Imaging .NET 15.0\Bin\JavaScript" в корневую папку проекта "vueapp1.client".

      • Скопируйте файлы Vintasoft.Imaging.css и Vintasoft.Imaging.Annotation.css из папки "<InstallPath>\VintaSoft Imaging .NET 15.0\Bin\JavaScript\" в корневую папку проекта "vueapp1.client".

      • Укажите, какие "стандартные" UI-диалоги должны спользоваться веб просмотрщиком документов
        • Если веб просмотрщик документов долен использовать готовые к использованию "стандартные" UI-диалоги Bootstrap:
          • Добавьте Node-модуль "bootstrap" в файл "package.json". Пересоберите проект для обновления Node-модулей.
            Вот исходные коды файла "package.json" после обновления:
            {
              "name": "vueapp1.client",
              "version": "0.0.0",
              "private": true,
              "type": "module",
              "engines": {
                "node": "^20.19.0 || >=22.12.0"
              },
              "scripts": {
                "dev": "vite",
                "build": "vite build",
                "preview": "vite preview",
                "lint": "eslint . --fix --cache"
              },
              "dependencies": {
                "vue": "^3.5.26"
              },
              "devDependencies": {
                "@eslint/js": "^9.39.2",
                "@vitejs/plugin-vue": "^6.0.3",
                "bootstrap": "~5.3.8",
                "eslint": "^9.39.2",
                "eslint-plugin-vue": "~10.6.2",
                "globals": "^17.0.0",
                "vite": "^7.3.0",
                "vite-plugin-vue-devtools": "^8.0.5"
              }
            }
            
            
          • Скопируйте файлы Vintasoft.Imaging.Dialogs.Bootstrap.js и Vintasoft.Imaging.DocumentViewer.Dialogs.Bootstrap.js из папки "<SdkInstallPath>\VintaSoft Imaging .NET 15.0\Bin\JavaScript\" в корневую папку проекта "vueapp1.client".

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

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

      • Добавьте ссылки на Vintasoft JavaScript-файлы в заголовок файла "index.html" в проекте "vueapp1.client".
        Добавьте ссылки на Vintasoft CSS-файлы в файл "index.html" в проекте "vueapp1.client".
        Добавьте ссылку на файл "bootstrap.css" в файл "index.html" в проекте "vueapp1.client".


        Вот исходные коды файла "index.html" после обновления:
        <!DOCTYPE html>
        <html lang="">
        <head>
            <meta charset="UTF-8">
            <link rel="icon" href="/favicon.ico">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <title>Vite App</title>
        
            <link rel="stylesheet" type="text/css" href="node_modules/bootstrap/dist/css/bootstrap.css" />
            <link rel="stylesheet" type="text/css" href="Vintasoft.Imaging.css">
            <link rel="stylesheet" type="text/css" href="Vintasoft.Imaging.Annotation.css">
        
            <script src="Vintasoft.Shared.js" type="text/javascript"></script>
            <script src="Vintasoft.Imaging.js" type="text/javascript"></script>
            <script src="Vintasoft.Imaging.Annotation.js" type="text/javascript"></script>
            <script src="Vintasoft.Imaging.DocumentViewer.js" type="text/javascript"></script>
            <script src="Vintasoft.Imaging.Dialogs.Bootstrap.js" type="text/javascript"></script>
            <script src="Vintasoft.Imaging.Annotation.Dialogs.Bootstrap.js" type="text/javascript"></script>
            <script src="Vintasoft.Imaging.DocumentViewer.Dialogs.Bootstrap.js" type="text/javascript"></script>
        </head>
        <body>
            <div id="app"></div>
            <script type="module" src="/src/main.js"></script>
        </body>
        </html>
        
        
    10. Проект "vueapp1.client": Создайте компонент Vue, позволяющий отображать документ, искать и извлекать текст из документа, а также аннотировать документ.

      • В проекте "vueapp1.client" в папке "src\components\" создайте файл "DocumentViewerDemo.vue", который будет содержать исходные коды Vue-компонента:
        • Выберите "Add => New Item..." контекстное меню для папки "src\components" в проекте "vueapp1.client" => появится UI-диалог "Add new item"
        • Установите шаблон "Vue TypeScript Template" из интернета, если шаблон не установлен в Visual Studio
        • Выберите тип "Vue TypeScript Template" для нового элемента
        • Установите "DocumentViewerDemo.vue" в качестве имени элемента
        • Нажмите кнопку "Add" => UI-диалог закроется и файл "DocumentViewerDemo.vue" будет добавлен в папку "src\components\"

        В файл DocumentViewerDemo.vue добавьте шаблон, который представляет заголовок приложения и div-элемент, который будет отображать веб просмотрщик документов:


        В файле DocumentViewerDemo.vue измените тип скрипта с TypeScript на JavaScript:


        В файле DocumentViewerDemo.vue добавьте функцию "mounted" (содержит JavaScript-код, который инициализирует и создает веб просмотрщик документов):


        В файле DocumentViewerDemo.vue добавьте CSS-стиль для Vue-компонента:


        Вот код HTML/CSS/JavaScript Vue-компонента DocumentViewerDemo:
        <template>
          <h1>VintaSoft Document Viewer (ASP.NET Core + Vue)</h1>
        
          <div id="documentViewerContainer" class="documentViewerContainer"></div>
        </template>
        
        <script lang="js">
          import { defineComponent } from 'vue';
        
          export default defineComponent({
            mounted() {
              setTimeout(__init, 500);
            }
          });
        
          function __init() {
                    // set the session identifier
                    Vintasoft.Shared.WebImagingEnviromentJS.set_SessionId("SessionID");
        
                    // specify web services, which should be used by Vintasoft Web Document Viewer
                    Vintasoft.Shared.WebServiceJS.defaultFileService =
                        new Vintasoft.Shared.WebServiceControllerJS("/vintasoft/api/MyVintasoftFileApi");
                    Vintasoft.Shared.WebServiceJS.defaultImageCollectionService =
                        new Vintasoft.Shared.WebServiceControllerJS("/vintasoft/api/MyVintasoftImageCollectionApi");
                    Vintasoft.Shared.WebServiceJS.defaultImageService =
                        new Vintasoft.Shared.WebServiceControllerJS("/vintasoft/api/MyVintasoftImageApi");
                    Vintasoft.Shared.WebServiceJS.defaultAnnotationService =
                        new Vintasoft.Shared.WebServiceControllerJS("/vintasoft/api/MyVintasoftAnnotationCollectionApi");
        
                    // create settings for document viewer with annotation support
                    var docViewerSettings =
                        new Vintasoft.Imaging.DocumentViewer.WebDocumentViewerSettingsJS("documentViewerContainer", { annotations: true });
        
                    // get items of document viewer
                    var items = docViewerSettings.get_Items();
        
                    // get the main menu of document viewer
                    var mainMenu = items.getItemByRegisteredId("mainMenu");
                    // if main menu is found
                    if (mainMenu != null) {
                        // get items of main menu
                        let mainMenuItems = mainMenu.get_Items();
        
                        // add "Annotation" menu panel to the main menu
                        mainMenuItems.addItem("annotationsMenuPanel");
                    }
        
                    // get side panel of document viewer
                    var sidePanel = items.getItemByRegisteredId("sidePanel");
                    // if side panel is found
                    if (sidePanel != null) {
                        // get items of side panel
                        let sidePanelItems = sidePanel.get_PanelsCollection();
        
                        // add "Annotations" panel to the side panel
                        sidePanelItems.addItem("annotationsPanel");
        
                        // add "Text selection" panel to the side panel
                        sidePanelItems.addItem("textSelectionPanel");
        
                        // add "Text searh" panel to the side panel
                        sidePanelItems.addItem("textSearchPanel");
                    }
        
                    // create the document viewer
                    var docViewer = new Vintasoft.Imaging.DocumentViewer.WebDocumentViewerJS(docViewerSettings);
        
                    // create visual tool that allows to work with annotations, navigate document and select text
                    var annotationNavigationTextSelectionTool =
                        docViewer.getVisualToolById("AnnotationVisualTool,DocumentNavigationTool,TextSelectionTool");
                    // specify visual tool as mandatory visual tool of document viewer
                    docViewer.set_MandatoryVisualTool(annotationNavigationTextSelectionTool);
                    // specify visual tool as current visual tool of document viewer
                    docViewer.set_CurrentVisualTool(annotationNavigationTextSelectionTool);
        
                    // get thumbnail viewer of document viewer
                    var thumbnailViewer = docViewer.get_ThumbnailViewer();
                    // specify that thumbnail viewer should not cache thumbnails on server side
                    thumbnailViewer.set_UseCache(false);
        
                    // get image viewer of document viewer
                    var imageViewer = docViewer.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");
          }
        </script>
        
        <style scoped>
          h1 {
            width: 1200px;
            text-align: center;
          }
        
          .documentViewerContainer {
            width: 1200px;
            height: 800px;
          }
        </style>
        
        

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


        Вот исходные коды файла "App.vue" после обновления:
        <script setup>
            import DocumentViewerDemo from './components/DocumentViewerDemo.vue'
        </script>
        
        <template>
            <main>
                <DocumentViewerDemo />
            </main>
        </template>
        
        <style scoped>
        </style>
        
        

      • Откройте файл "vite.config.js" в проекте "vueapp1.client" и укажите, что приложение Vue.js может получить доступ к ASP.NET Core Web API контроллеру "/vintasoft/api/" в проекте "VueApp1.Server":
        import { fileURLToPath, URL } from 'node:url';
        
        import { defineConfig } from 'vite';
        import plugin from '@vitejs/plugin-vue';
        import fs from 'fs';
        import path from 'path';
        import child_process from 'child_process';
        import { env } from 'process';
        
        const baseFolder =
            env.APPDATA !== undefined && env.APPDATA !== ''
                ? `${env.APPDATA}/ASP.NET/https`
                : `${env.HOME}/.aspnet/https`;
        
        const certificateName = "vueapp1.client";
        const certFilePath = path.join(baseFolder, `${certificateName}.pem`);
        const keyFilePath = path.join(baseFolder, `${certificateName}.key`);
        
        if (!fs.existsSync(baseFolder)) {
            fs.mkdirSync(baseFolder, { recursive: true });
        }
        
        if (!fs.existsSync(certFilePath) || !fs.existsSync(keyFilePath)) {
            if (0 !== child_process.spawnSync('dotnet', [
                'dev-certs',
                'https',
                '--export-path',
                certFilePath,
                '--format',
                'Pem',
                '--no-password',
            ], { stdio: 'inherit', }).status) {
                throw new Error("Could not create certificate.");
            }
        }
        
        const target = env.ASPNETCORE_HTTPS_PORT ? `https://localhost:${env.ASPNETCORE_HTTPS_PORT}` :
            env.ASPNETCORE_URLS ? env.ASPNETCORE_URLS.split(';')[0] : 'https://localhost:7140';
        
        // https://vitejs.dev/config/
        export default defineConfig({
            plugins: [plugin()],
            resolve: {
                alias: {
                    '@': fileURLToPath(new URL('./src', import.meta.url))
                }
            },
            server: {
                proxy: {
                    '^/vintasoft/api/': {
                        target,
                        secure: false
                    }
                },
                port: parseInt(env.DEV_SERVER_PORT || '63870'),
                https: {
                    key: fs.readFileSync(keyFilePath),
                    cert: fs.readFileSync(certFilePath),
                }
            }
        })
        
        

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