šŸ—‚ļø HRImagingController Documentation

Path: IrbyImaging/Controllers/HRImagingController.cs
Assembly: IrbyImaging.UI
Author: sdoucet
Created: 07‑10‑2023
Last Modified: 07‑10‑2023


šŸ“‘ Table of Contents

  1. Overview & Purpose
  2. Dependencies & Technologies
  3. Controller Structure & Class Diagram
  4. Key Functional Areas
  5. Data Models & ViewModels
  6. Helper Methods & Utilities
  7. Error Handling & Return Types
  8. Sample Code Snippets
  9. UML Class Diagram (Mermaid)
  10. 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 TempDocumentData and binary streams in BlobData.
    • 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’ ImageOCRContents into a single PDF for download/view.

3. Indexing & Saving Documents

Once pages are previewed:

  1. SaveDocument (Step 1) — Assigns an IndexTag, populates drop‐down lists for
    Document Types & Index fields.
  2. Save (Step 2) — Collects user‐entered index values, packs pages into one PDF,
    uploads to Azure Blob Storage, and writes a DocumentImage record.
[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 — Takes DocumentImaging with index criteria, filters DocumentImages
    by JSON‐serialized DocumentIndexes, 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 under wwwroot/IrbyHR.
  • FileOperations: single POST endpoint to process EJ2 FileManager commands:
    read / delete / copy / move / details / create / search / rename.
  • Azure Blob interaction:
    • BlobServiceClient injected; uses container irbyimaging.
    • 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 ViewBag messages.
  • FileManager errors return FileManagerResponse.Error with HTTP status codes.
  • PDF Viewer API returns textual error or JSON payload.
  • Unauthorized access to blob uses redirect to UnAuthorized action.
  • ResponseCache disabled for Error action.

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! šŸš€