Asp.Net MVC how to get view to generate PDF

前端 未结 8 1472
醉酒成梦
醉酒成梦 2020-11-28 19:09

I would like to call an action on a controller. Have the controller get the data from the model. The view then runs and generates a PDF. The only example I have found i

8条回答
  •  有刺的猬
    2020-11-28 20:05

    Very Late Reply, but I found that the following URL helped me get my results quickly :

    (Ensure that you reference to the iTextSharp DLL by making use of the Nuget Packages)

    https://www.aspsnippets.com/Articles/Export-Grid-Html-Table-data-from-database-to-PDF-file-using-iTextSharp-in-ASPNet-MVC.aspx

    EDIT This is the code I used to make the table look a little different(This is landscape as well:

    public string GetCssForPdf()
            {
                string css = "";
    
                css = "th, td" +
                       "{" +
                           "font-family:Arial; font-size:10px" +
                        "}";
    
                return css;
            }
    
    [HttpPost]
            [ValidateInput(false)]
            public FileResult Export(string GridHtml)
            {
                string webgridstyle = GetCssForPdf();
    
                string exportData = String.Format("{0}{1}", "", GridHtml);
                var bytes = System.Text.Encoding.UTF8.GetBytes(exportData);
    
                using (var input = new MemoryStream(bytes))
                {
                    var output = new MemoryStream();
                    var document = new iTextSharp.text.Document(PageSize.A4, 50, 50, 50, 50);
                    var writer = PdfWriter.GetInstance(document, output);
    
                    document.SetPageSize(iTextSharp.text.PageSize.A4.Rotate());
                    Font headerFont = FontFactory.GetFont("Verdana", 10);
                    Font rowfont = FontFactory.GetFont("Verdana", 10);
    
                    writer.CloseStream = false;
                    document.Open();
    
                    var xmlWorker = iTextSharp.tool.xml.XMLWorkerHelper.GetInstance();
                    xmlWorker.ParseXHtml(writer, document, input, System.Text.Encoding.UTF8);
                    document.Close();
                    output.Position = 0;
    
                    return File(output, "application/pdf", "Pipeline_Report.pdf");
    
                    //return new FileStreamResult(output, "application/pdf");
                }
            }
    

    Hope this helps someone else as well.

提交回复
热议问题