1

我的 Controller 类中有两个操作方法:

  1. DetailsAll:获取一些数据并显示在视图中
  2. SaveAsPDF:在 DetailsAll.cshtml 的 windows.load 上调用,应将 DetailsAll 视图保存为 pdf

我的问题在于 SaveAsPDF Action 方法。在这里,我尝试使用 Rotativa ActionAsPdf 和随后的 BuildFile 方法来生成和保存 PDF。但是,在执行“BuildFile”行时,它没有在我的 DetailsAll Action 方法中命中断点,随后导致 PDF 生成空白。

你能帮我解决我哪里出错了吗?

    [HttpGet]
    public ActionResult DetailsAll()
    {
        var selectionBuilder = builderFactory.GetGeocodeReportSelectionViewModelBuilder();
        var companyList = selectionBuilder.Build();

        List<GeocodeReportViewModel> viewModel = new List<GeocodeReportViewModel>();
        foreach(SelectListItem record in companyList.Companies)
        {
            var builder = builderFactory.GetGeocodeReportViewModelBuilder(int.Parse(record.Value));
            viewModel.Add(builder.Build());
        }
        var model = new AllGeocodeReportViewModel
        {
            GeocodeReports = viewModel
        };
        return View(model);
    }

    [HttpGet]
    public string SaveAsPDF()
    {
        var report = new ActionAsPdf("DetailsAll")
        {
            FileName = "OEM_GeocodeReport_" + System.DateTime.Now.ToString("MMYY") + ".pdf",
            PageSize = Size.A4,
            PageOrientation = Orientation.Landscape,
            PageMargins = { Left = 1, Right = 1 }
        };
        byte[] pdf = report.BuildFile(ControllerContext);
        System.IO.File.WriteAllBytes("C:\\" + report.FileName, pdf);
        return "true";
    }


   
4

1 回答 1

0

经过大量搜索终于找到了问题。我需要将身份验证 cookie 与 BuildFile 请求一起发送才能正常工作。添加了以下代码,它现在可以正确生成 PDF:

 public void SaveAsPDF()
    {
        var cookies = Request.Cookies.AllKeys.ToDictionary(k => k, k => Request.Cookies[k].Value);
        var report = new ActionAsPdf("DetailsAll")
        {
            FileName = "OEM_GeocodeReport_" + System.DateTime.Now.ToString("MMyy") + ".pdf",
            PageSize = Size.A4,
            PageOrientation = Orientation.Portrait,
            PageMargins = { Left = 3, Right = 3 },
            FormsAuthenticationCookieName = System.Web.Security.FormsAuthentication.FormsCookieName,
            Cookies = cookies
        };
        byte[] pdf = report.BuildFile(ControllerContext);
        System.IO.File.WriteAllBytes("C:\\" + report.FileName, pdf);            
    }
于 2021-06-02T16:04:30.837 回答