šļø HRImagingController Documentation
Path:
IrbyImaging/Controllers/HRImagingController.cs
Assembly: IrbyImaging.UI
Author: sdoucet
Created: 07ā10ā2023
Last Modified: 07ā10ā2023
š Table of Contents
- Overview & Purpose
- Dependencies & Technologies
- Controller Structure & Class Diagram
- Key Functional Areas
- Data Models & ViewModels
- Helper Methods & Utilities
- Error Handling & Return Types
- Sample Code Snippets
- UML Class Diagram (Mermaid)
- Conclusion
š 1. Overview & Purpose
The HRImagingController is the central MVC controller for HRārelated document imaging in the IrbyImaging.UI web application. It provides:
- Upload & Preview of multiāpage PDF and image documents.
- OCR (Optical Character Recognition) via IronOCR / IronPDF.
- Indexing & Tagging documents against types, categories, and attributes.
- Storage of pages and metadata in a SQL database and Azure Blob Storage.
- Listing & Searching capabilities over indexed HR documents.
- CRUD Operations for document Categories, Types, and Attributes.
- File Manager integration for direct filesystem browsing.
- PDF Viewer API endpoints for paging, annotations, thumbnails (Syncfusion EJ2).
- Word & Excel support via Syncfusion DocIO and XlsIO.
This controller extends a BaseController and is decorated with [DisableRequestSizeLimit] to allow large file uploads.
āļø 2. Dependencies & Technologies
| Category | Package/Namespace | Purpose |
|---|---|---|
| ASP.NET Core MVC | Microsoft.AspNetCore.Mvc, IWebHostEnvironment |
Web framework, hosting environment |
| Data Access | IrbyImaging.DomainClasses, Microsoft.EntityFrameworkCore |
EF Core, DB context |
| Authentication | Microsoft.AspNetCore.Identity |
ASP.NET Core Identity |
| File I/O | Syncfusion.EJ2.FileManager.PhysicalFileProvider |
Virtual file system |
| PDF Manipulation | iTextSharp.text.pdf, iTextSharp.text.pdf.parser |
Splitting/merging PDF pages |
| OCR | IronOcr |
Text extraction from images/PDFs |
| PDF Generation | IronPdf |
Create searchable PDF |
| File Viewer & Annotation | Syncfusion.EJ2.PdfViewer, Syncfusion.DocIO, Syncfusion.EJ2.DocumentEditor |
PDF viewer & Word editing |
| Spreadsheet | Syncfusion.XlsIO, Syncfusion.EJ2.Spreadsheet |
Excel import/export |
| JSON | Newtonsoft.Json |
JSON serialization |
| Caching | Microsoft.Extensions.Caching.Memory |
In-memory caching for PDF pages |
| Cloud Storage | Azure.Storage.Blobs |
Azure Blob Storage interaction |
š 3. Controller Structure & Class Diagram
classDiagram
HRImagingController --> IrbyContext : _context
HRImagingController --> IHttpContextAccessor : _httpContextAccessor
HRImagingController --> IWebHostEnvironment : _hostingEnvironment
HRImagingController --> IMemoryCache : _cache
HRImagingController --> BlobServiceClient : _blobServiceClient
HRImagingController --> IConfiguration : _configuration
HRImagingController : +IActionResult Index()
HRImagingController : +IActionResult Upload()
HRImagingController : +Task<IActionResult> UploadDocs(file)
HRImagingController : +ActionResult DocPreview(fileName, batchId)
HRImagingController : +Task<ActionResult> Preview(id)
HRImagingController : +ActionResult List()
HRImagingController : +IActionResult List(image, form)
HRImagingController : +ActionResult RenderImage(id, preview)
HRImagingController : +ActionResult Save(image, form, batchId, roles)
HRImagingController : +IActionResult DocumentTypes()
HRImagingController : +IActionResult DocumentCategories()
HRImagingController : +IActionResult DocumentAttributes()
HRImagingController : +ActionResult FileManager()
HRImagingController : +IActionResult Load(jsonObjects)
HRImagingController : +ActionResult FileOperations(args)
HRImagingController : +IActionResult GetDocuments(param)
HRImagingController : +IActionResult GetExcel(param)
HRImagingController : +IActionResult SaveExcel(saveSettings)
šÆ 4. Key Functional Areas
1. Document Upload & Preview
- GET
/HRImaging/Uploadā Returns upload form. - POST
/HRImaging/UploadDocs- Splits each uploaded PDF into separate pageāPDFs using iTextSharp.
- Stores pages in
TempDocumentDataand binary streams inBlobData. - Assigns a BatchId to group pages.
- Redirects to DocPreview.
[HttpPost]
[RequestSizeLimit(900_000_000)]
public async Task<IActionResult> UploadDocs(IEnumerable<IFormFile> file) {
var batchId = Guid.NewGuid();
foreach (IFormFile doc in file) {
using var target = new MemoryStream();
doc.CopyTo(target);
PdfReader sourcePDF = new PdfReader(target.ToArray());
for (int i=1; i<=sourcePDF.NumberOfPages; i++) {
// extract single page -> MemoryStream newPDFStream ...
// create TempDocumentData + BlobData
}
_context.SaveChanges();
}
return RedirectToAction("DocPreview", new { batchId = batchId.ToString() });
}
- GET
/HRImaging/DocPreview?batchId=ā¦- Displays preview thumbnails, page count, āsingleāpage uploadā flag.
2. OCR & PDF Processing
- OCRResult ā Uses IronTesseract to deskew, OCR input (image or PDF), and produce:
ImageOCRText(plain text)ImageOCRContents(searchable PDF bytes)
public DocumentImaging OCRResult(...) {
using var input = new OcrInput();
input.AddPdf(path);
input.Deskew();
var ocrOutput = ocr.Read(input);
doc.ImageOCRContents = ocrOutput.SaveAsSearchablePdfBytes();
doc.ImageOCRText = ocrOutput.Text;
return doc;
}
- ViewOCR(Guid id) ā Merges all pagesā
ImageOCRContentsinto a single PDF for download/view.
3. Indexing & Saving Documents
Once pages are previewed:
- SaveDocument (Step 1) ā Assigns an IndexTag, populates dropādown lists for
Document Types & Index fields. - Save (Step 2) ā Collects userāentered index values, packs pages into one PDF,
uploads to Azure Blob Storage, and writes aDocumentImagerecord.
[HttpPost]
public async Task<IActionResult> Save(DocumentImaging image, IFormCollection form, string batchId, List<string> roles) {
// Merge PDF pages, extract text via Syncfusion.PdfViewer,
// Upload blob: containerClient.GetBlobClient("HumanResources/"+filename).UploadAsync(...)
// Save DocumentImage entity with DocumentIndexes = JsonSerialize(options)
}
4. Listing, Searching & Filtering
- GET
/HRImaging/Listā Populates available Document Types & Index fields for search. - POST
/HRImaging/Listā TakesDocumentImagingwith index criteria, filtersDocumentImages
by JSONāserializedDocumentIndexes, and returns matching results.
5. CRUD for Categories / Types / Attributes
| Entity | Endpoints | View Model |
|---|---|---|
| Category | /DocumentCategories, /CreateCategory, /EditCategory/{id}, /DeleteCategory/{id} |
DocumentCategoryView & Detail |
| Type | /DocumentTypes, /CreateType, /EditType/{id}, /DeleteType/{id} |
DocumentTypeView & Detail |
| Attribute | /DocumentAttributes, /CreateAttribute, /EditAttribute/{id}, /DeleteAttribute/{id} |
DocumentAttributeView & Detail |
Each CRUD action sets IsAvailable, IsDeleted, AddedBy, ModifiedBy metadata and saves via _context.
6. File Management & Azure Blob Storage
- PhysicalFileProvider (
operation) for onādisk File Manager underwwwroot/IrbyHR. - FileOperations: single POST endpoint to process EJ2 FileManager commands:
read / delete / copy / move / details / create / search / rename. - Azure Blob interaction:
BlobServiceClientinjected; uses containerirbyimaging.- Document pages and final PDFs/attachments live in Azure.
7. PDF Viewer API Endpoints
Syncfusion EJ2 PDF Viewer integration under [Route("api/[controller]/*")]:
| Endpoint | Action |
|---|---|
| Load | Load PDF or Base64 stream into viewer |
| RenderPdfPages | Get page as image tile |
| RenderThumbnailImages | Retrieve page thumbnails |
| RenderAnnotationComments | Get annotations on a page |
| Bookmarks | Retrieve PDF bookmarks |
| Download | Export PDF as base64 |
| PrintImages | Get printable page images |
| ExportAnnotations | Export annotations JSON |
| ImportAnnotations | Load existing annotations from file |
| Unload | Clear PDF viewer cache |
All accept JSON objects or jsonObjects DTO and return JSON responses.
8. Excel & Word Document Support
- Word (
.docx,.doc,.rtf, etc.) via Syncfusion.EJ2.DocumentEditor- GetDocuments returns base64 PDF or JSON representation of Word doc.
- Excel via Syncfusion.XlsIO / EJ2 Spreadsheet
- GetExcel, OpenExcel, SaveExcel endpoints for importing/exporting spreadsheets.
š§© 5. Data Models & ViewModels
| DTO/ViewModel | Purpose |
|---|---|
| DocumentImaging | Main VM for indexing/viewing document pages |
| DocumentImagingList | Represents a single search result entry |
| DocumentTypeView & Detail | CRUD view for DocumentType |
| DocumentCategoryView & Detail | CRUD view for DocumentCategory |
| DocumentAttributeView & Detail | CRUD view for DocumentAttribute |
| HRDocumentCategories | Aggregates categories with HRDocumentCategoryDetail |
| TempDocumentData | Temporary storage of pageālevel uploads |
| BlobData | Binary data blobs for temp documents |
| DocumentImage | Final persisted PDF/image metadata |
| IndexOptions | Helper to serialize index values for a document |
| FileManagerDirectoryContent | EJ2 FileManager request params |
| jsonObjects | DTO for PDF viewer API |
| CustomParams | DTO for Word/Excel loader |
| AccessRoles, DocumentCollections | Helper classes for multiāselect lists |
š ļø 6. Helper Methods & Utilities
| Method | Description |
|---|---|
| GetUserName(string user) | Lookup userās full name via Azure AD |
| SaveDocumentAndReturnPath | Merges pages into PDF file on disk for preview |
| ModifyAttachedDocs | Rebuilds merged PDF after page deletion |
| Combine(byte[],byte[]) | Concatenates two byte arrays |
| JsonConverterstring | Flattens jsonObjects into Dictionary<string,string> |
| GetFormatType(string) | Maps file extension to Syncfusion.EJ2.DocumentEditor.FormatType |
šØ 7. Error Handling & Return Types
- Model Validation errors return to view with
ViewBagmessages. - FileManager errors return
FileManagerResponse.Errorwith HTTP status codes. - PDF Viewer API returns textual error or JSON payload.
- Unauthorized access to blob uses redirect to
UnAuthorizedaction. - ResponseCache disabled for
Erroraction.
Return types vary by action:
- IActionResult / ActionResult / FileContentResult for browser views/files.
- Json(...) for AJAX API calls.
- Content(...) for base64 string or JSON content.
š” 8. Sample Code Snippets
8.1 Splitting a PDF into SingleāPage Streams
using var target = new MemoryStream();
doc.CopyTo(target);
var source = new PdfReader(target.ToArray());
for (int i = 1; i <= source.NumberOfPages; i++) {
using var newPDFStream = new MemoryStream();
var pdfDoc = new Document(PageSize.A4);
var pdfCopy = new PdfCopy(pdfDoc, newPDFStream);
pdfDoc.Open();
pdfCopy.AddPage(pdfCopy.GetImportedPage(source, i));
pdfDoc.Close();
byte[] pageBytes = newPDFStream.ToArray();
// Save pageBytes into TempDocumentData & BlobData
}
8.2 Merging Pages into a Single PDF
public string SaveDocumentAndReturnPath(string[] docIds) {
var pages = _context.TempDocumentData
.Where(d => docIds.Contains(d.TempDocumentDataId.ToString()))
.OrderBy(d => d.DocumentUploadedDate).ToList();
using var ms = new MemoryStream();
using var merged = new Document();
using var copier = new PdfSmartCopy(merged, ms);
merged.Open();
foreach (var p in pages) {
using var reader = new PdfReader(p.ImageContents);
copier.AddDocument(reader);
}
merged.Close();
// Write ms.ToArray() to disk or blob...
}
8.3 Invoking the PDF Viewer āLoadā API via AJAX
fetch('/api/HRImaging/Load', {
method: 'POST',
headers: { 'Content-Type':'application/json' },
body: JSON.stringify({ document: 'data:application/pdf;base64,...', isFileName:false })
})
.then(r => r.json())
.then(viewerData => {
// initialize Syncfusion PDF viewer with viewerData
});
š 9. UML Class Diagram (Mermaid)
classDiagram
%% Core Dependencies
HRImagingController *-- IrbyContext
HRImagingController *-- IHttpContextAccessor
HRImagingController *-- IWebHostEnvironment
HRImagingController *-- IMemoryCache
HRImagingController *-- BlobServiceClient
%% Major Functions
HRImagingController : +Index()
HRImagingController : +UploadDocs(...)
HRImagingController : +DocPreview(...)
HRImagingController : +List(...)
HRImagingController : +Save(...)
HRImagingController : +DocumentTypes()
HRImagingController : +DocumentCategories()
HRImagingController : +DocumentAttributes()
HRImagingController : +FileOperations(...)
HRImagingController : +Load(jsonObjects)
HRImagingController : +GetDocuments(CustomParams)
š 10. Conclusion
The HRImagingController is a comprehensive MVC controller built to manage the full lifecycle of HR document imaging:
- From upload, pageālevel storage, and OCR,
- To indexing, search, and metadata management,
- Providing rich PDF viewer features, Word/Excel editing,
- And an integrated file manager for direct file system access.
It leverages multiple thirdāparty libraries (iTextSharp, IronOCR, IronPDF, Syncfusion) and Azure Blob Storage to offer a robust, enterpriseāgrade document management solution in the IrbyImaging platform.
Feel free to explore each region in the controller, inspect the ViewModels under IrbyImaging.UI.Models, and adapt or extend for additional requirements! š