Добавление веб просмотрщика документов в "React + ASP.NET Core" приложение
В этом разделе
В этом руководстве показано, как создать пустое "React + ASP.NET Core" приложение в Visual Studio .NET 2022 и добавить веб просмотрщик документов (с возможностью открывать изображения и документы (PDF, DOCX, XLSX), извлекать/искать текст, комментировать документы) в "React + ASP.NET Core" приложение.
Вот шаги, которые необходимо выполнить:
-
Создайте пустое "React + ASP.NET Core" приложение.
-
Откройте Visual Studio .NET 2022 и создайте новое приложение типа "React + ASP.NET Core":
-
Настройте приложение для использования .NET 8.0:
-
Серверная часть: Добавьте ссылки на .NET-сборки Vintasoft в проект "ReactApp1.Server".
Скопируйте файлы 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" проекта "ReactApp1.Server" и добавьте ссылки на .NET-сборки в проект "ReactApp1.Server".
-
Серверная сторона: Укажите движок рисования, который должен использоваться 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-графики
-
Серверная сторона: Создайте веб сервисы, которые позволяют загружать/скачивать файлы, управлять коллекцией изображений, получать информацию об изображениях, получать миниатюры, рендерить тайлы изображений, извлекать/искать текст и комментировать документ.
-
Создайте веб сервис, позволяющий загружать/скачивать файл
-
Нажмите правую кнопку мыши на папке "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)
{
}
}
}
-
Создайте веб сервис, который позволяет комментировать изображения и документы
-
Нажмите правую кнопку мыши на папке "Controllers" и выберите меню "Add => Controller..." из контекстного меню
-
Выберите шаблон "Empty API controller", установите имя контроллера "MyVintasoftAnnotationCollectionApiController" и нажмите кнопку "Add".
-
Укажите, что класс MyVintasoftAnnotationCollectionApiController является производным от класса Vintasoft.Imaging.Annotation.AspNetCore.ApiControllers.VintasoftAnnotationCollectionApiController
Вот исходные коды класса MyVintasoftAnnotationCollectionApiController:
namespace ReactApp1.Server.Controllers
{
public class MyVintasoftAnnotationCollectionApiController :
Vintasoft.Imaging.Annotation.AspNetCore.ApiControllers.VintasoftAnnotationCollectionApiController
{
public MyVintasoftAnnotationCollectionApiController(IWebHostEnvironment hostingEnvironment)
: base(hostingEnvironment)
{
}
}
}
-
Серверная сторона: Создайте 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.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();
-
Серверная сторона: Добавьте Newtonsoft JSON для десериализации JSON-аннотаций.
-
Добавьте ссылку на nuget-пакет Microsoft.AspNetCore.Mvc.NewtonsoftJson.
-
Откройте файл "Program.cs" в проекте "ReactApp1.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();
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();
-
Серверная сторона: Обновите стартовый URL-адрес приложения в файле "launchSettings.json".
-
Откройте файл "Properties\launchSettings.json" в "ReactApp1.Server" и очистите стартовый URL-адрес приложения:
-
Сторона сервера: Скопируйте тестовый PDF документ по умолчанию на сторону сервера.
- Создайте папку "UploadedImageFiles\SessionID" в проекте "ReactApp1.Server" и скопируйте тестовый PDF документ "<SdkInstallPath>\VintaSoft\Imaging .NET 14.0\Examples\ASP.NET Core\CSharp\AspNetCoreImagingDemo\wwwroot\UploadedImageFiles \VintasoftImagingDemo.pdf" в папку. Этот документ будет отображен в веб просмотрщике документов.
Скомпилируйте проект для восстановления зависимостей с помощью 'npm'
-
Удалите файлы, которые не нужны в этом руководстве.
-
Удалите файлы "WeatherForecast.cs" и "Controllers\WeatherForecastController.cs" в проекте "ReactApp1.Server" - ASP.NET Core Web API контроллер WeatherForecast не требуется в этом руководстве.
- Удалите файлы "src\App.css" и "src\App.jsx" - этот React-компонент не требуется в этом руководстве.
-
Клиентская сторона: Добавьте JavaScript-файлы в проект "reactapp1.client".
-
Скопируйте файлы Vintasoft.Shared.js, Vintasoft.Imaging.js, Vintasoft.Imaging.Annotation.js и Vintasoft.Imaging.DocumentViewer.js из папки "<SdkInstallPath>\VintaSoft Imaging .NET 14.0\Bin\JavaScript\" в папку "public".
-
Укажите, какие "стандартные" UI-диалоги (UI-диалог ввода пароля, UI-диалог печати и т. д.) должны использоваться веб просмотрщик документов
-
Если веб просмотрщик документов долен использовать готовые к использованию "стандартные" 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.DocumentViewer.Dialogs.Bootstrap.js из папки "<SdkInstallPath>\VintaSoft Imaging .NET 14.0\Bin\JavaScript" в папку "public".
-
Если веб просмотрщик документов должен использовать готовые к использованию "стандартные" 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 14.0\Bin\JavaScript" в папку "src\app\assets".
-
Если веб просмотрщик документов должно использовать пользовательские "стандартные" UI-диалоги, прочтите, как создавать пользовательские "стандартные" UI-диалоги
здесь
.
-
Скопируйте файлы Vintasoft.Imaging.css и Vintasoft.Imaging.Annotation.css с CSS-стилями 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.Annotation.css">
<link rel="stylesheet" type="text/css" href="src/DocumentViewerDemo.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.Annotation.js" type="text/javascript"></script>
<script src="public/Vintasoft.Imaging.DocumentViewer.js" type="text/javascript"></script>
<script src="public/Vintasoft.Imaging.Dialogs.Bootstrap.js" type="text/javascript"></script>
<script src="public/Vintasoft.Imaging.Annotation.Dialogs.Bootstrap.js" type="text/javascript"></script>
<script src="public/Vintasoft.Imaging.DocumentViewer.Dialogs.Bootstrap.js" type="text/javascript"></script>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.jsx"></script>
</body>
</html>
-
Добавьте CSS-стиль "documentViewerContainer", определяющий размер контейнера веб просмотрщика документов, в файл "src\DocumentViewerDemo.css":
Вот исходные коды файла "DocumentViewerDemo.css":
h1 {
width: 1200px;
text-align: center;
}
.documentViewerContainer {
width: 1200px;
height: 800px;
}
-
Клиентская часть: Создайте React-компонент, который позволяет отображать документ, искать и извлекать текст из документа, аннотировать документ.
-
Создайте файл "DocumentViewerDemo.jsx", который будет содержать исходные коды React-компонента (класс DocumentViewerDemo):
- Выберите контекстное меню "Add => New Item..." для папкb "src\" => Появится UI-диалог "Add new item"
- Выберите тип "JSX-файл" для нового элемента
- Установите "DocumentViewerDemo.jsx" в качестве имени элемента
- Нажмите кнопку "Add" => UI-диалог закроется и файл "DocumentViewerDemo.jsx" будет добавлен в папку "src\".
Добавьте объявление класса DocumentViewerDemo с функцией 'render' (отображает заголовок приложения и div-элемент, который будет отображать веб просмотрщик документов) в файл "DocumentViewerDemo.jsx":
Добавьте функцию "comComponentDidMount" (содержит JavaScript-код, который инициализирует и создает веб просмотрщик документов) в класс DocumentViewerDemo:
Важно:
Visual Studio использует случайный сетевой порт для ASP.NET Core API, и вам необходимо обновить JavaScript-код и изменить URL-адрес веб-службы с "https://localhost:7240/" на URL-адрес в вашем приложение.
Вот JavaScript-код файла "DocumentViewerDemo.jsx":
import { Component } from 'react';
export class DocumentViewerDemo extends Component {
static displayName = DocumentViewerDemo.name;
static _isInitialized = false;
render() {
return (
<div>
<h1>VintaSoft Document Viewer Demo (ASP.NET Core + React.js)</h1>
<div id="documentViewerContainer" className="documentViewerContainer"></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 Document Viewer
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.defaultAnnotationService =
new Vintasoft.Shared.WebServiceControllerJS("https://localhost:7240/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
let items = docViewerSettings.get_Items();
// get the main menu of document viewer
let 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
let 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
let docViewer = new Vintasoft.Imaging.DocumentViewer.WebDocumentViewerJS(docViewerSettings);
// create visual tool that allows to work with annotations, navigate document and select text
let 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
let 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
let 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");
}
}
-
Добавьте созданный React-компонент в код React-приложения - файл "src\main.jsx":
Вот исходные коды файла "main.jsx" после обновления:
import React from 'react'
import ReactDOM from 'react-dom/client'
import { DocumentViewerDemo } from './DocumentViewerDemo.jsx'
import './index.css'
ReactDOM.createRoot(document.getElementById('root')).render(
<React.StrictMode>
<DocumentViewerDemo />
</React.StrictMode>,
)
-
Запустите "React + ASP.NET Core" приложение и посмотрите результат.