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.

One Comment on “Generate PDF in ASP.NET Core”

  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 *