13

I need to generate a PDF from a HTML Canvas, but the process must complete on the server side which is an ASP.NET Core Web Api.

hem
  • 1,012
  • 6
  • 11
Sorin B.
  • 151
  • 1
  • 1
  • 4
  • 1
    there aren't any built-in option/feature in `ASP.NET` to generate PDF. You either have to use a Server-Side library like [ItextSharp](https://itextpdf.com/en) or use a Client-Side library like [jsPDF](https://parall.ax/products/jspdf) or some tutorials like [Convert HTML table to PDF using pdfmake](https://www.aspsnippets.com/Articles/Convert-Export-HTML-Table-to-PDF-file-using-JavaScript.aspx) or any of your choice. – vikscool Sep 27 '19 at 10:02
  • There is a good library aspos to do conversion on the server side. However it will be paid. – mukesh joshi Sep 27 '19 at 12:00

2 Answers2

7

On the server-side, you can output HTML of a view as string and can use any library that generate PDF from HTML string. to render a view into string see this link Return View as String in .NET Core after you got HTML, you need to pass it to the library see this link to convert HTML to string Convert HTML to PDF in .NET

1 Create a C# extension method to render view to string

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewEngines;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using System.IO;
using System.Threading.Tasks;

namespace CC.Web.Helpers
{
    public static class ControllerExtensions
    {
        public static async Task<string> RenderViewAsync<TModel>(this Controller controller, string viewName, TModel model, bool partial = false)
        {
            if (string.IsNullOrEmpty(viewName))
            {
                viewName = controller.ControllerContext.ActionDescriptor.ActionName;
            }

            controller.ViewData.Model = model;

            using (var writer = new StringWriter())
            {
                IViewEngine viewEngine = controller.HttpContext.RequestServices.GetService(typeof(ICompositeViewEngine)) as ICompositeViewEngine;
                ViewEngineResult viewResult = viewEngine.FindView(controller.ControllerContext, viewName, !partial);

                if (viewResult.Success == false)
                {
                    return $"A view with the name {viewName} could not be found";
                }

                ViewContext viewContext = new ViewContext(
                controller.ControllerContext,
                viewResult.View,
                controller.ViewData,
                controller.TempData,
                writer,
                new HtmlHelperOptions()
            );

                await viewResult.View.RenderAsync(viewContext);

                return writer.GetStringBuilder().ToString();
            }
        }
    }
} 

2) Render view to string

viewHtml = await this.RenderViewAsync("Report", model);

3) Use HTML to create PDF

    Byte[] res = null;
    using (MemoryStream ms = new MemoryStream())
    {
        var pdf = TheArtOfDev.HtmlRenderer.PdfSharp.PdfGenerator.GeneratePdf(viewHtml, PdfSharp.PageSize.A4);
        pdf.Save(ms);
        res = ms.ToArray();
    }
Arjun Vachhani
  • 1,761
  • 3
  • 21
  • 44
  • 2
    Thankyou so much for taking time and mentioning the best combination after so much research. I also after doing a lot of research found that you took the best possible combinations of all the steps and combined it in a single answer. Thankyou again for your hardwork – Hamza Khanzada Apr 04 '20 at 15:02
  • 6
    PdfSharp doesnt support .net core though? – treendy Aug 16 '20 at 19:06
  • Steps 1 & 2 can be simplified with this ready to use nuget package https://github.com/soundaranbu/RazorTemplating – Soundar Anbu May 31 '21 at 15:03
2
using IronPdf;
IronPdf.HtmlToPdf Renderer = new IronPdf.HtmlToPdf();
// Render an HTML document or snippet as a string
Renderer.RenderHtmlAsPdf("<h1>Hello World</h1>").SaveAs("html-string.pdf");
// Advanced: 
// Set a "base url" or file path so that images, javascript and CSS can be loaded  
var PDF = Renderer.RenderHtmlAsPdf("<img src='icons/iron.png'>",@"C:\site\assets\");
PDF.SaveAs("html-with-assets.pdf");

IronPDF for .NET Core

barnacle.m
  • 2,070
  • 3
  • 38
  • 82
RezaGhahari
  • 405
  • 3
  • 9