Export a webgrid to pdf asp mvc razor

How to export a webgrid to a .pdf file in an mvc .net web application?

Answers


Here's a couple of ways to do it:

  • You can use RazorPDF as mentioned in the previous response
  • You can use Rotativa. Which works very fast, but you need permissions to run the server on Full Trust, as the PDF transformation occurs on an executable file
  • You can use iTextSharp which would be the most difficult/cumbersome to implement, but at the same time you have all the flexibility to write the PDF document as you wish

Hope that helps-


For complete reference, please follow How to Export Webgrid to PDF in MVC4 Application

Create an action link to your view page

<div>
     Export Data : @Html.ActionLink("Export to PDF","GETPdf","Webgrid")
</div>

then create an MVC Action for export webgrid data to pdf file. Here iTextSharp.dll used for export pdf file.

public FileStreamResult GETPdf()
    {
        List<CustomerInfo> all = new List<CustomerInfo>();
        using (MyDatabaseEntities dc = new MyDatabaseEntities())
        {
            all = dc.CustomerInfoes.ToList();
        }

        WebGrid grid = new WebGrid(source: all, canPage: false, canSort: false);
        string gridHtml = grid.GetHtml(
                columns: grid.Columns(
                        grid.Column("CustomerID", "Customer ID"),
                        grid.Column("CustomerName", "Customer Name"),
                        grid.Column("Address", "Address"),
                        grid.Column("City", "City"),
                        grid.Column("PostalCode", "Postal Code")
                    )
                ).ToString();

        string exportData = String.Format("<html><head>{0}</head><body>{1}</body></html>", "<style>table{ border-spacing: 10px; border-collapse: separate; }</style>", 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);
            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 new FileStreamResult(output, "application/pdf");
        }

Need Your Help

Str::title no longer working in Laravel 5

php laravel laravel-5

I have the code below that worked in Laravel 4.2 but no longer in Laravel 5. Str::title() is no longer working. If I echo out $development after the title runs, it is all in uppercase. However, ...

Dynamically add CSS stylesheets in JavaFX

java css javafx

I would like to add a CSS file which is located somewhere on the filesystem.