Search code examples
c#asp.net-corerotativa

Rotativa Cannot perform runtime binding on a null reference asp.net core


problem

I am trying to create pdf in asp.net core using Rotativa but it throw me an error. I want to create html and convert it to pdf and then store in on server directory

Error

enter image description here

code

[HttpPost]
    public IActionResult Index(Invoice invoice)
    {
        var webRoot = _env.WebRootPath;

        var pdf = new ViewAsPdf("Index")
        {
            FileName = "Test.pdf",
            PageSize = Rotativa.AspNetCore.Options.Size.A4,
            PageOrientation = Rotativa.AspNetCore.Options.Orientation.Portrait,
            PageHeight = 20,
            
        };

        var byteArray = pdf.BuildFile(ControllerContext).Result;
        //var fileStream = new MemoryStream(Path.Combine(webRoot, pdf.FileName), FileMode.Create, FileAccess.Write);
        var memoryStream = new MemoryStream(byteArray, 0, byteArray.Length);
    }

Solution

  • Answer

    The error indicates that you haven't configured Rotativa.

    Configuration your application like this:

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        app.UseStaticFiles();
        app.UseMvcWithDefaultRoute();
        Rotativa.AspNetCore.RotativaConfiguration.Setup(env);
    }
    

    Also add wkhtmltopdf.exe to wwwroot like this:

    wwwroot
        Rotativa
            wkhtmltopdf.exe
    

    Once you have done that, the following will work.

    public async Task<IActionResult> Index()
    {
        var pdf = new Rotativa.AspNetCore.ViewAsPdf("Index")
        {
            FileName = "C:\\Test.pdf",
            PageSize = Rotativa.AspNetCore.Options.Size.A4,
            PageOrientation = Rotativa.AspNetCore.Options.Orientation.Portrait,
            PageHeight = 20,
        };
    
        var byteArray = await pdf.BuildFile(ControllerContext);
        return File(byteArray, "application/pdf");
    }
    

    Note the use of async/await instead of using .Result.

    See also: