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

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

    Откройте Visual Studio .NET 2019, создайте новый проект типа "ASP.NET Web Application" и настройте его для использования .NET Framework 4.7.2:

    Выберите шаблон "Empty" для ASP.NET приложения и настройте проект для использования MVC и Web API:

  2. На стороне сервера: Добавьте ссылки на .NET-сборки Vintasoft в ASP.NET MVC 5 приложение.

    Добавьте ссылки на .NET-сборки Vintasoft.Shared.dll, Vintasoft.Imaging.dll, Vintasoft.Imaging.Annotation.dll, Vintasoft.Imaging.Pdf.dll, Vintasoft.Imaging.Office.OpenXml.dll, Vintasoft.Shared.Web.dll, Vintasoft.Imaging.Web.Services.dll, Vintasoft.Imaging.Annotation.Web.Services.dll, Vintasoft.Imaging.Web.Api2Controllers.dll и Vintasoft.Imaging.Annotation.Web.Api2Controllers.dll из папки "<SdkInstallPath>\VintaSoft Imaging .NET 14.1\Bin\DotNet4\AnyCPU\" в ASP.NET MVC 5 приложение.



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

    ASP.NET MVC5 приложение должно использовать библиотеку System.Drawing в качестве графического движка, поскольку ASP.NET MVC5 приложение может использоваться только в Windows.

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

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

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

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

        Вот исходные коды класса MyVintasoftFileApiController:
        namespace WebApplication1.Controllers
        {
            public class MyVintasoftFileApiController : Vintasoft.Imaging.Web.Api2Controllers.VintasoftFileApi2Controller
            {
        
                public MyVintasoftFileApiController()
                    : base()
                {
                }
        
            }
        }
        
        

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

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

        Вот исходные коды класса MyVintasoftImageCollectionApiController:
        namespace WebApplication1.Controllers
        {
            public class MyVintasoftImageCollectionApiController :
                Vintasoft.Imaging.Web.Api2Controllers.VintasoftImageCollectionApi2Controller
            {
        
                public MyVintasoftImageCollectionApiController()
                    : base()
                {
                }
        
            }
        }
        
        

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

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

        Вот исходные коды класса MyVintasoftImageApiController:
        namespace WebApplication1.Controllers
        {
            public class MyVintasoftImageApiController : Vintasoft.Imaging.Web.Api2Controllers.VintasoftImageApi2Controller
            {
        
                public MyVintasoftImageApiController()
                    : base()
                {
                }
        
            }
        }
        
        

    • Создайте веб сервис, который позволяет комментировать изображения и документы

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

        Вот исходные коды класса MyVintasoftAnnotationCollectionApiController:
        namespace WebApplication1.Controllers
        {
            public class MyVintasoftAnnotationCollectionApiController :
                Vintasoft.Imaging.Annotation.Web.Api2Controllers.VintasoftAnnotationCollectionApi2Controller
            {
        
                public MyVintasoftAnnotationCollectionApiController()
                    : base()
                {
                }
        
            }
        }
        
        

    • Откройте файл "App_Start\WebApiConfig.cs" и проверьте, правильно ли ASP.NET MVC приложение регистрирует маршрут для Web API контроллера.

      Вот C# код файла WebApiConfig.cs:
      using System.Web.Http;
      
      namespace WebApplication1
      {
          public static class WebApiConfig
          {
              public static void Register(HttpConfiguration config)
              {
                  config.Routes.MapHttpRoute(
                      name: "DemoAPI",
                      routeTemplate: "vintasoft/api/{controller}/{action}"
                  );
              }
          }
      }
      
      
  5. На стороне сервера: Создайте ASP.NET MVC 5 контроллер для веб-представления, которое будет отображать веб просмотрщик документов.

    • Нажмите правую кнопку мыши на папке "Controllers" и выберите меню "Add => Controller..." из контекстного меню


    • Выберите шаблон "MVC 5 Controller - Empty", укажите имя контроллера "DefaultController" и нажмите кнопку "Add".


    • Откройте файл "App_Start\RouteConfig.cs" и проверьте, правильно ли ASP.NET MVC 5 приложение регистрирует маршрут для MVC-контроллера.

      Вот C# код файла RouteConfig.cs:
      using System.Web.Mvc;
      using System.Web.Routing;
      
      namespace WebApplication1
      {
          public class RouteConfig
          {
              public static void RegisterRoutes(RouteCollection routes)
              {
                  routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
      
                  routes.MapRoute(
                      name: "Default",
                      url: "{controller}/{action}",
                      defaults: new { controller = "Default", action = "Index" }
                  );
              }
          }
      }
      
      
      
  6. На стороне сервера: Проверьте глобальную конфигурацию ASP.NET MVC 5 приложения.

    Откройте файл "Global.asax.cs" и убедитесь, что метод "Application_Start" регистрирует все области в ASP.NET MVC приложении, настраивает глобальную HTTP-конфигурацию для ASP.NET приложения и регистрирует маршруты для ASP.NET MVC приложения.

    Вот C# код файла Global.asax.cs:
    using System.Web.Http;
    using System.Web.Mvc;
    using System.Web.Routing;
    
    namespace WebApplication1
    {
        public class MvcApplication : System.Web.HttpApplication
        {
            protected void Application_Start()
            {
                // specify that VintaSoft Imaging .NET SDK should use System.Drawing (GDI+) library for drawing of 2D graphics
                Vintasoft.Imaging.Drawing.Gdi.GdiGraphicsFactory.SetAsDefault();
    
                AreaRegistration.RegisterAllAreas();
                GlobalConfiguration.Configure(WebApiConfig.Register);
                RouteConfig.RegisterRoutes(RouteTable.Routes);
            }
        }
    }
    
  7. На стороне клиента: Создайте веб-представление для отображения веб просмотрщика документов.

    • Откройте файл "DefaultController.cs", щёлкните правой кнопкой мыши по методу "Index" класса DefaultController и выберите в контекстном меню пункт "Add View...".
    • Выберите шаблон "MVC 5 View", нажмите кнопку "Add", укажите "Index" в качестве имени представления, снимите флажок "Use a layout page" и нажмите кнопку "Add" => будет создан файл "Views\Default\Index.cshtml".
  8. На стороне клиента: Добавьте JavaScript-библиотеки в проект.

    • Добавьте папку "Scripts\" в ASP.NET MVC приложение (если папка отсутствует).

    • Скопируйте файлы Vintasoft.Shared.js, Vintasoft.Imaging.js, Vintasoft.Imaging.css, Vintasoft.Imaging.Annotation.js, Vintasoft.Imaging.Annotation.css и Vintasoft.Imaging.DocumentViewer.js из папки "\VintaSoft Imaging .NET 14.1\Bin\JavaScript\" в папку "Scripts\".

    • Укажите, какие "стандартные" UI-диалоги (UI-диалог ввода пароля, UI-диалог печати и т. д.) должны использоваться веб просмотрщик документов
      • Если веб просмотрщик документов должен использовать готовые к использованию "стандартные" UI-диалоги jQuery UI:
        • Скопируйте файл jQuery в папку "Scripts\".
          Вы можете использовать файл "jquery-3.3.1.min.js" из папки "\VintaSoft Imaging .NET 14.1\Examples\ASP.NET MVC\CSharp\AspNetMvcImagingDemo\Scripts\External\" или файл jQuery из любого другого источника.
        • Скопируйте файлы и папки jQuery UI в папку "Scripts\".
          Вы можете использовать файл "jquery-ui.min.js" и папку "jquery-ui-css" из папки "\VintaSoft Imaging .NET 14.1\Examples\ASP.NET MVC\CSharp\AspNetMvcImagingDemo\Scripts\External\" или файлы и папки jQuery UI из любого другого источника.
        • Скопируйте файлы Vintasoft.Imaging.Dialogs.jQueryUI.js и Vintasoft.Imaging.DocumentViewer.Dialogs.jQueryUI.js из папки "\VintaSoft Imaging .NET 14.1\Bin\JavaScript\" folder into "Scripts\".

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

    • Создайте папку "UploadedImageFiles\SessionID" и скопируйте тестовый PDF документ "<SdkInstallPath>\VintaSoft\Imaging .NET 14.1\Images\VintasoftImagingDemo.pdf" в созданную папку. Этот документ будет отображаться в веб просмотрщике документов.

    • Откройте веб-представление - файл "Views\Default\Index.cshtml".


    • Добавьте ссылки на JavaScript-файлы Vintasoft:

      Вот HTML-код, который добавляет ссылки на файлы jQuery и JavaScript-файлы Vintasoft:
      <style>
          * {
              -webkit-box-sizing: border-box;
              box-sizing: border-box;
              border-collapse: collapse;
          }
      </style>
      
      <link rel="stylesheet" type="text/css" href="~/Scripts/jquery-ui-css/jquery-ui.min.css">
      <link rel="stylesheet" type="text/css" href="~/Scripts/Vintasoft.Imaging.css">
      <link rel="stylesheet" type="text/css" href="~/Scripts/Vintasoft.Imaging.Annotation.css">
      
      <script src="~/Scripts/jquery-3.3.1.min.js" type="text/javascript"></script>
      <script src="~/Scripts/jquery-ui.min.js" type="text/javascript"></script>
      
      <script src="~/Scripts/Vintasoft.Shared.js" type="text/javascript"></script>
      <script src="~/Scripts/Vintasoft.Imaging.js" type="text/javascript"></script>
      <script src="~/Scripts/Vintasoft.Imaging.Dialogs.jQueryUI.js" type="text/javascript"></script>
      <script src="~/Scripts/Vintasoft.Imaging.Annotation.js" type="text/javascript"></script>
      <script src="~/Scripts/Vintasoft.Imaging.Annotation.Dialogs.jQueryUI.js" type="text/javascript"></script>
      <script src="~/Scripts/Vintasoft.Imaging.DocumentViewer.js" type="text/javascript"></script>
      <script src="~/Scripts/Vintasoft.Imaging.DocumentViewer.Dialogs.jQueryUI.js" type="text/javascript"></script>
      


    • Добавьте в веб-представление HTML-разметку (div-элемент, который будет отображать веб просмотрщик документов):

      Вот код HTML-разметки:
      <h1 style="text-align: center">VintaSoft Document Viewer Demo (ASP.NET Core MVC5)</h1>
      
      <div id="documentViewerContainer" style="height: 800px"></div>
      


    • Добавьте JavaScript-код, который инициализирует и создаёт веб просмотрщик документов:

      Вот JavaScript-код, который инициализирует и создаёт веб просмотрщик документов:
      @{
          Layout = null;
      }
      
      <!DOCTYPE html>
      
      <html>
      <head>
          <meta name="viewport" content="width=device-width" />
          <title>VintaSoft Document Viewer Demo (ASP.NET MVC5)</title>
      
          <style>
              * {
                  -webkit-box-sizing: border-box;
                  box-sizing: border-box;
                  border-collapse: collapse;
              }
          </style>
      
          <link rel="stylesheet" type="text/css" href="~/Scripts/jquery-ui-css/jquery-ui.min.css">
          <link rel="stylesheet" type="text/css" href="~/Scripts/Vintasoft.Imaging.css">
          <link rel="stylesheet" type="text/css" href="~/Scripts/Vintasoft.Imaging.Annotation.css">
      
          <script src="~/Scripts/jquery-3.3.1.min.js" type="text/javascript"></script>
          <script src="~/Scripts/jquery-ui.min.js" type="text/javascript"></script>
      
          <script src="~/Scripts/Vintasoft.Shared.js" type="text/javascript"></script>
          <script src="~/Scripts/Vintasoft.Imaging.js" type="text/javascript"></script>
          <script src="~/Scripts/Vintasoft.Imaging.Dialogs.jQueryUI.js" type="text/javascript"></script>
          <script src="~/Scripts/Vintasoft.Imaging.Annotation.js" type="text/javascript"></script>
          <script src="~/Scripts/Vintasoft.Imaging.Annotation.Dialogs.jQueryUI.js" type="text/javascript"></script>
          <script src="~/Scripts/Vintasoft.Imaging.DocumentViewer.js" type="text/javascript"></script>
          <script src="~/Scripts/Vintasoft.Imaging.DocumentViewer.Dialogs.jQueryUI.js" type="text/javascript"></script>
      </head>
      <body>
          <h1 style="text-align: center">VintaSoft Document Viewer Demo (ASP.NET Core MVC5)</h1>
      
          <div id="documentViewerContainer" style="height: 800px"></div>
      
          <script type="text/javascript">
              // 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
              let 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
                  var 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);
      
              // open file from session folder and add images from file to the image viewer
              docViewer.openFile("VintasoftImagingDemo.pdf");
          </script>
      </body>
      </html>
      
      
  10. Запустите ASP.NET MVC5 приложение и посмотрите результат.