简体   繁体   中英

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

在此处输入图片说明

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);
    }

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:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM