Search code examples
c#razorasp.net-core-mvcpdf-generationrotativa

Display dynamic header using Rotativa pdf in MVC net core


I want to display dynamic header in a cshtml. When i try to pass it using CustomSwitches i get an error like QPaintDevice: Cannot destroy paint device that is being paintedpure virtual method called terminate called without an active exception.

Calling Rotativa component(it's in a class library) from mvc Controller to print the dynamic view without header works correctly but not with the header. Is there anyway to solve this problem?

Thank you for your answers.

Edit: Example using Rotativa

string header = $"/Header.cshtml";

var customSwitches = string.Format("--header-html "{0}" " + "--header-spacing "0" ", header);

        var view = new ViewAsPdf(pdfView.ToViewRoute(culture), model: viewModel)
        {
            PageOrientation = option.PageOrientation,
            IsGrayScale = option.IsGrayScale,
            MinimumFontSize = option.MinimumFontSize,
            PageSize = option.PageSize,
            PageMargins = option.PageMargins,
            CustomSwitches = customSwitches
        };
        return view;

Solution

  • customSwitches may not find /header.cshml. You need to give the correct path.

        [HttpGet]
        public IActionResult Pdf()
        {
            string customSwitches = string.Format(" --print-media-type --page-offset 2 --footer-center [page] --allow {0} --footer-html {0} --footer-spacing -180 ",
                Url.Action("header", "home", new { area = "" }, "https"));
            var pageList = new List<tbpage>();
            pageList.Add(new tbpage()
            {
                page_name = "1",
                page_no = "a"
            });
            return new ViewAsPdf("PdfDemo", model: pageList)
                {
                    PageOrientation = Rotativa.AspNetCore.Options.Orientation.Portrait,  
                    IsGrayScale = true,
                    MinimumFontSize = 20,
                     PageSize = Rotativa.AspNetCore.Options.Size.A5,
                     PageMargins = { Left = 20, Bottom = 20, Right = 20, Top = 20 },
                    CustomSwitches = customSwitches
            };
        }
    

    Model

    public class tbpage
    {
        public string page_name { get; set; }
        public string page_no { get; set; }
    }
    

    Pdf

    enter image description here

    In addition, if it is still incorrect, please add [AllowAnonymous] to the action Header. You can also refer to answer.

    [AllowAnonymous]
    public ActionResult Header()
    {
        return View();
    }