Generate PDF in ASP.NET Core

Generate PDF

If we write application in version MVC 5 or less. We can use simple to use library like Rotativa. But what if we have apps on ASP.NET MVC Core. Many library is not compatibile with Core yet. I will show you on example how to deal with it.

Example

First, we need to install wkhtmltopdf. Then in our application we’ll need to use WKWrap.Core library.

public IActionResult DownloadPdf()
{
    var htmlContent = "<div>Hi</div>";
    var wkhtmltopdf = new FileInfo(@"C:\Program Files\wkhtmltopdf\bin\wkhtmltopdf.exe");
    var converter = new HtmlToPdfConverter(wkhtmltopdf);
    var pdfBytes = converter.ConvertToPdf(htmlContent);

    FileResult fileResult = new FileContentResult(pdfBytes, "application/pdf");
    fileResult.FileDownloadName = "test.pdf";
    return fileResult;
}

Above action will return us file pdf with the inscription “Hi”.

Now we can add function that will convert view in the form of a string.

Here is link to example how to write that RenderingViewToString class.

public async Task<IActionResult> DownloadPdf()
{
    var htmlContent = await _viewRenderService.RenderToStringAsync("Home/About", new object());
    var wkhtmltopdf = new FileInfo(@"C:\Program Files\wkhtmltopdf\bin\wkhtmltopdf.exe");
    var converter = new HtmlToPdfConverter(wkhtmltopdf);
    var pdfBytes = converter.ConvertToPdf(htmlContent);

    FileResult fileResult = new FileContentResult(pdfBytes, "application/pdf");
    fileResult.FileDownloadName = "test.pdf";
    return fileResult;
}

With this way you can generate any pdf from any view.

renderViewToString

Link to project.

2 Comments on “Generate PDF in ASP.NET Core”

  1. This works in development. On production, I get a 500 internal server error and when I troubleshoot, I get the error, nullreference exception at the line 0 referencing the html page in var htmlContent = await _viewRenderService.RenderToStringAsync(“Home/About”, new object()). In visual studio 2017, I get the pdf as intended. But i get the abovementioned error in IIS deployment. Please how do I resolve this?

    1. Please check the path of wkhtmltopdf.exe on your production host and/or check if IIS has permission for this path.

Leave a Reply

Your email address will not be published. Required fields are marked *