2025-05-22 13:35:27 -07:00

74 lines
2.6 KiB
C#

#if NET8
using System;
using System.IO;
using System.Threading.Tasks;
using Fab2ApprovalSystem.PdfGenerator;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewEngines;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Microsoft.Extensions.DependencyInjection;
namespace Fab2ApprovalSystem.Extensions;
public static class ControllerExtensions {
public static ActionResult GetBinaryContentResult<TModel>(this Controller controller, string viewName, string contentType, TModel model) {
string pageTitle = string.Empty;
string htmlText = RenderViewToString(controller, viewName, model);
StandardPdfRenderer standardPdfRenderer = new();
// Let the html be rendered into a PDF document through iTextSharp.
byte[] buffer = standardPdfRenderer.Render(htmlText, pageTitle);
// Return the PDF as a binary stream to the client.
return new BinaryContentResult(buffer, contentType);
}
public static string RenderViewToString<TModel>(this Controller controller, string viewName, TModel model) {
if (string.IsNullOrEmpty(viewName))
viewName = controller.ControllerContext.ActionDescriptor.ActionName;
controller.ViewData.Model = model;
using (StringWriter writer = new()) {
try {
CompositeViewEngine compositeViewEngine = controller.HttpContext.RequestServices.GetRequiredService(typeof(ICompositeViewEngine)) as CompositeViewEngine;
if (compositeViewEngine is null || compositeViewEngine.ViewEngines.Count == 0) { }
ViewEngineResult viewResult = null;
if (viewName.EndsWith(".cshtml"))
viewResult = compositeViewEngine.GetView(viewName, viewName, false);
else
viewResult = compositeViewEngine.FindView(controller.ControllerContext, viewName, false);
if (!viewResult.Success)
return $"A view with the name '{viewName}' could not be found";
ViewContext viewContext = new(
controller.ControllerContext,
viewResult.View,
controller.ViewData,
controller.TempData,
writer,
new HtmlHelperOptions()
);
Task task = viewResult.View.RenderAsync(viewContext);
task.Wait();
return writer.GetStringBuilder().ToString();
} catch (Exception ex) {
return $"Failed - {ex.Message}";
}
}
}
}
#endif