代码之家  ›  专栏  ›  技术社区  ›  Malik Kashmiri

Rotativa无法对空引用ASP.NET核心执行运行时绑定

  •  2
  • Malik Kashmiri  · 技术社区  · 6 年前

    问题

    我正在尝试使用rotativa在ASP.NET核心中创建PDF,但它给了我一个错误。 我想创建HTML并将其转换为PDF,然后存储在服务器目录中

    错误

    代码

    [httppost]
    公共影响结果索引(发票发票)
    {
    var webroot=_env.webrootpath;
    
    var pdf=new viewaspdf(“索引”)。
    {
    filename=“test.pdf”,
    pagesize=rotativa.aspnetcore.options.size.a4,
    pageOrientation=rotativa.aspnetcore.options.Orientation.Portrait,
    页面高度=20,
    
    };
    
    var bytearray=pdf.buildfile(controllerContext.result);
    //var filestream=new memorystream(path.combine(webroot,pdf.filename),filemode.create,fileaccess.write);
    var memoryStream=新的memoryStream(bytearray,0,bytearray.length);
    }
    
    
    

    误差

    enter image description here

    代码

    [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);
        }
    
    1 回复  |  直到 6 年前
        1
  •  5
  •   Shaun Luttin    6 年前

    回答

    错误表明您尚未配置rotativa。

    像这样配置应用程序:

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

    同时添加 wkhtmltopdf.exe 要这样做:

    wwwroot
        Rotativa
            wkhtmltopdf.exe
    

    一旦你做到了,下面的工作就可以了。

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

    注意使用 async/await 而不是使用 .Result .

    另请参见:

    推荐文章