Добавление веб просмотрщика документов в ASP.NET Core приложение
В этом разделе
Данное руководство демонстрирует, как создать пустое ASP.NET Core приложение в Visual Studio .NET 2022 и добавить веб просмотрщик документов (с возможностью открытия изображений и документов (PDF, DOCX, XLSX), извлечения/поиска текста, аннотирования документов) в ASP.NET Core приложение.
Вот шаги, которые необходимо выполнить:
-
Создайте пустое ASP.NET Core приложение.
Откройте Visual Studio .NET 2022 и создайте новый проект типа "ASP.NET Core Web Application":
Настройте проект для использования .NET 8.0:
-
На стороне сервера: Добавьте ссылки на .NET-сборки Vintasoft в ваше ASP.NET Core приложение.
Скопируйте .NET-сборки Vintasoft.Shared.dll, Vintasoft.Imaging.dll, Vintasoft.Imaging.Pdf.dll, Vintasoft.Imaging.Annotation.dll, Vintasoft.Imaging.Annotation.Pdf.dll, Vintasoft.Imaging.Office.OpenXml, Vintasoft.Shared.Web.dll, Vintasoft.Imaging.Web.Services.dll, Vintasoft.Imaging.Annotation.Web.Services.dll, Vintasoft.Imaging.AspNetCore.ApiControllers.dll и Vintasoft.Imaging.Annotation.AspNetCore.ApiControllers.dll из папки "<SdkInstallPath>\VintaSoft Imaging .NET 14.0\Bin\DotNet8\AnyCPU\" в папку "Bin" ASP.NET Core приложения и добавьте ссылки на .NET-сборки в ASP.NET Core приложение.
-
Серверная сторона: Укажите движок рисования, который должен использоваться VintaSoft Imaging .NET SDK для рисования 2D-графики.
Если ASP.NET Core приложение планируется использовать в среде Windows или Linux, рекомендуется применять графический движок SkiaSharp.
Если ASP.NET Core приложение будет использоваться только в среде Windows, можно применять как графический движок System.Drawing, так и SkiaSharp.
Вот шаги, которые необходимо выполнить для использования движка SkiaSharp:
-
Добавьте ссылку на .NET-сборку Vintasoft.Imaging.Drawing.SkiaSharp.dll.
- Добавьте ссылку на nuget-пакет SkiaSharp версии 2.88.9.
- Откройте файл "Startup.cs" и добавьте строку кода "Vintasoft.Imaging.Drawing.SkiaSharp.SkiaSharpDrawingFactory.SetAsDefault();" в начало метода ConfigureServices - добавленный код указывает VintaSoft Imaging .NET SDK использовать библиотеку SkiaSharp для отрисовки 2D-графики.
Вот шаги, которые необходимо выполнить для использования движка System.Drawing:
-
Добавьте ссылку на .NET-сборку Vintasoft.Imaging.Gdi.dll.
- Откройте файл "Startup.cs" и добавьте строку кода "Vintasoft.Imaging.Drawing.Gdi.GdiGraphicsFactory.SetAsDefault();" в начало метода ConfigureServices - добавленный код указывает VintaSoft Imaging .NET SDK использовать библиотеку System.Drawing для отрисовки 2D-графики.
-
Серверная сторона: Создайте веб сервисы, которые позволяют загружать/скачивать файлы, управлять коллекцией изображений, получать информацию об изображениях, получать миниатюры, рендерить тайлы изображений, извлекать/искать текст и комментировать документ.
- Добавьте в проект папку "Controllers".
-
Создайте веб сервис, позволяющий загружать/скачивать файл
-
Нажмите правую кнопку мыши на папке "Controllers" и выберите меню "Add => Controller..." из контекстного меню
-
Выберите шаблон "Empty API controller", установите имя контроллера "MyVintasoftFileApiController" и нажмите кнопку "Add".
-
Укажите, что класс MyVintasoftFileApiController является производным от класса Vintasoft.Imaging.AspNetCore.ApiControllers.VintasoftFileApiController
Вот исходные коды класса MyVintasoftFileApiController:
using Microsoft.AspNetCore.Hosting;
namespace WebApplication1.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:
using Microsoft.AspNetCore.Hosting;
namespace WebApplication1.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:
using Microsoft.AspNetCore.Hosting;
namespace WebApplication1.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:
using Microsoft.AspNetCore.Hosting;
namespace WebApplication1.Controllers
{
public class MyVintasoftAnnotationCollectionApiController :
Vintasoft.Imaging.Annotation.AspNetCore.ApiControllers.VintasoftAnnotationCollectionApiController
{
public MyVintasoftAnnotationCollectionApiController(IWebHostEnvironment hostingEnvironment)
: base(hostingEnvironment)
{
}
}
}
-
На стороне сервера: Добавьте Newtonsoft JSON для десериализации аннотаций.
- Добавьте ссылку на nuget-пакет Microsoft.AspNetCore.Mvc.NewtonsoftJson.
-
На стороне сервера: Создайте MVC-контроллер для веб-представления, которое будет отображать веб просмотрщик документов.
-
Нажмите правую кнопку мыши на папке "Controllers" и выберите меню "Add => Controller..." из контекстного меню
-
Выберите шаблон "MVC Controller - Empty", укажите имя контроллера "DefaultController" и нажмите кнопку "Add".
-
Откройте файл "Startup.cs" и добавьте контроллеры с представлениями в сервисы ASP.NET Core приложения:
Добавьте созданный MVC-контроллер в конечные точки ASP.NET Core приложения:
Включите обслуживание статических файлов для текущего пути запроса ASP.NET Core приложения:
Вот C# код файла Startup.cs:
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace WebApplication1
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// specify that VintaSoft Imaging .NET SDK should use SkiaSharp library for drawing of 2D graphics
Vintasoft.Imaging.Drawing.SkiaSharp.SkiaSharpDrawingFactory.SetAsDefault();
// add Newtonsoft JSON for deserialization of JSON annotations
services.AddControllersWithViews().AddNewtonsoftJson();
services.AddRazorPages();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute("default", "{controller=Default}/{action=Index}/{id?}");
});
}
}
}
-
Клиентская сторона: Создайте веб представление для отображения редактора PDF документа.
-
Откройте файл "DefaultController.cs", щёлкните правой кнопкой мыши по методу "Index" класса DefaultController и выберите в контекстном меню пункт "Add View...".
-
Выберите шаблон "Razor View - Empty", нажмите кнопку "Добавить", задайте имя представления "Index" и нажмите кнопку "Добавить" => Будет создан файл "Views\Default\Index.cshtml"
-
На стороне клиента: Добавьте JavaScript-библиотеки в проект.
-
Добавьте папку "wwwroot\js\" в ASP.NET Core приложение (если папка отсутствует).
- Скопируйте файлы 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.0\Bin\JavaScript\" в папку "wwwroot\js\".
-
Укажите, какие "стандартные" UI-диалоги (UI-диалог ввода пароля, UI-диалог печати и т. д.) должны использоваться веб просмотрщик документов
-
Если веб просмотрщик документов долен использовать готовые к использованию "стандартные" UI-диалоги Bootstrap:
- Добавьте библиотеки Bootstrap и jQuery в проект.
- скопируйте файлы Vintasoft.Imaging.Dialogs.Bootstrap.js и Vintasoft.Imaging.DocumentViewer.Dialogs.Bootstrap.js из папки "\VintaSoft Imaging .NET 14.0\Bin\JavaScript\" в папку "wwwroot\js\".
-
Если веб просмотрщик документов должен использовать готовые к использованию "стандартные" UI-диалоги jQuery UI:
- добавьте библиотеки jQuery и jQuery UI в проект;
- скопируйте файлы Vintasoft.Imaging.Dialogs.jQueryUI.js и Vintasoft.Imaging.DocumentViewer.Dialogs.jQueryUI.js из папки "\VintaSoft Imaging .NET 14.0\Bin\JavaScript\" в папку "wwwroot\js\".
-
Если веб просмотрщик документов должно использовать пользовательские "стандартные" UI-диалоги, прочтите, как создавать пользовательские "стандартные" UI-диалоги
здесь
.
-
На стороне клиента: Добавьте JavaScript-код, который позволяет отображать документы, искать и извлекать текст, аннотировать документы.
-
Создайте папку "wwwroot\UploadedImageFiles\SessionID" и скопируйте тестовый PDF документ "<SdkInstallPath>\VintaSoft\Imaging .NET 14.0\Images\VintasoftImagingDemo.pdf" в созданную папку. Этот документ будет отображаться в веб просмотрщике документов.
-
Откройте веб-представление - файл "Views\Default\Index.cshtml".
-
Добавьте ссылки на используемые JavaScript-библиотеки:
-
Если вы используете диалоговые окна Bootstrap, добавьте ссылки на файлы Bootstrap и Vintasoft JavaScript-файлы.
Вот HTML-код, который добавляет ссылки на файлы Bootstrap и Vintasoft JavaScript-файлы:
<link rel="stylesheet" type="text/css" href="~/js/jquery-ui-css/jquery-ui.min.css">
<link rel="stylesheet" type="text/css" href="~/js/Vintasoft.Imaging.css">
<link rel="stylesheet" type="text/css" href="~/js/Vintasoft.Imaging.Annotation.css">
<script src="~/js/Vintasoft.Shared.js" type="text/javascript"></script>
<script src="~/js/Vintasoft.Imaging.js" type="text/javascript"></script>
<script src="~/js/Vintasoft.Imaging.Annotation.js" type="text/javascript"></script>
<script src="~/js/Vintasoft.Imaging.DocumentViewer.js" type="text/javascript"></script>
<script src="~/js/Vintasoft.Imaging.Dialogs.Bootstrap.js" type="text/javascript"></script>
<script src="~/js/Vintasoft.Imaging.Annotation.Dialogs.Bootstrap.js" type="text/javascript"></script>
<script src="~/js/Vintasoft.Imaging.DocumentViewer.Dialogs.Bootstrap.js" type="text/javascript"></script>
-
Если вы используете диалоговые окна jQuery UI, добавьте ссылки на jQuery-файлы и Vintasoft JavaScript-файлы.
Вот HTML-код, который добавляет ссылки на jQuery-файлы и Vintasoft JavaScript-файлы:
<link rel="stylesheet" type="text/css" href="~/js/jquery-ui-css/jquery-ui.min.css">
<link rel="stylesheet" type="text/css" href="~/js/Vintasoft.Imaging.css">
<link rel="stylesheet" type="text/css" href="~/js/Vintasoft.Imaging.Annotation.css">
<script src="~/js/jquery-3.3.1.min.js" type="text/javascript"></script>
<script src="~/js/jquery-ui.min.js" type="text/javascript"></script>
<script src="~/js/Vintasoft.Shared.js" type="text/javascript"></script>
<script src="~/js/Vintasoft.Imaging.js" type="text/javascript"></script>
<script src="~/js/Vintasoft.Imaging.Annotation.js" type="text/javascript"></script>
<script src="~/js/Vintasoft.Imaging.DocumentViewer.js" type="text/javascript"></script>
<script src="~/js/Vintasoft.Imaging.Dialogs.jQueryUI.js" type="text/javascript"></script>
<script src="~/js/Vintasoft.Imaging.Annotation.Dialogs.jQueryUI.js" type="text/javascript"></script>
<script src="~/js/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)</h1>
<div id="documentViewerContainer" style="height:800px"></div>
-
Добавьте JavaScript-код, который инициализирует и создаёт веб просмотрщик документов:
Вот JavaScript-код, который инициализирует и отображает веб просмотрщик документов:
<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
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
var 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);
// get image viewer of document viewer
var imageViewer = docViewer.get_ImageViewer();
// open file from session folder and add images from file to the image viewer
imageViewer.get_Images().openFile("VintasoftImagingDemo.pdf");
</script>
-
Запустите веб-приложение ASP.NET Core и посмотрите результат.