Export Generic Collection to PDF ASP.Net Core MVC

Export Generic Collection to PDF ASP.Net Core MVC

PDF

Sometime you may in need to export data in PDF. Following code will use Syncfusion Package and give you ready made Table pushed from Generic collection.

Put below code in Repository

public static JsonResult ExportToPDF<T>(List<T> list, string filename)
        {
            //Create a new PDF document
            PdfDocument document = new PdfDocument();
            //Add a page to the document
            PdfPage page = document.Pages.Add();
            //Create PDF graphics for the page
            PdfGraphics graphics = page.Graphics;

            //Set the standard font
            PdfFont font = new PdfStandardFont(PdfFontFamily.Helvetica, 20);

            //Draw the text
            //graphics.DrawString("Hello World!!!", font, PdfBrushes.Black, new PointF(0, 0));
            //Creates a PDF grid
            PdfGrid grid = new PdfGrid();
            //Adds the data source
            grid.DataSource = list;
            //Creates the grid cell styles
            PdfGridCellStyle cellStyle = new PdfGridCellStyle();
            cellStyle.Borders.All = PdfPens.White;
            PdfGridRow header = grid.Headers[0];
            //Creates the header style
            PdfGridCellStyle headerStyle = new PdfGridCellStyle();
            headerStyle.Borders.All = new PdfPen(new PdfColor(126, 151, 173));
            headerStyle.BackgroundBrush = new PdfSolidBrush(new PdfColor(126, 151, 173));
            headerStyle.TextBrush = PdfBrushes.White;
            headerStyle.Font = new PdfStandardFont(PdfFontFamily.TimesRoman, 14f, PdfFontStyle.Regular);
            for (int i = 0; i < header.Cells.Count; i++)
            {
                if (i == 0 || i == 1)
                    header.Cells[i].StringFormat = new PdfStringFormat(PdfTextAlignment.Left, PdfVerticalAlignment.Middle);
                else
                    header.Cells[i].StringFormat = new PdfStringFormat(PdfTextAlignment.Right, PdfVerticalAlignment.Middle);
            }
            //Applies the header style
            header.ApplyStyle(headerStyle);
            cellStyle.Borders.Bottom = new PdfPen(new PdfColor(217, 217, 217), 0.70f);
            cellStyle.Font = new PdfStandardFont(PdfFontFamily.TimesRoman, 12f);
            cellStyle.TextBrush = new PdfSolidBrush(new PdfColor(131, 130, 136));
            //Creates the layout format for grid
            PdfGridLayoutFormat layoutFormat = new PdfGridLayoutFormat();
            // Creates layout format settings to allow the table pagination
            layoutFormat.Layout = PdfLayoutType.Paginate;
            //Draws the grid to the PDF page.
            PdfGridLayoutResult gridResult = grid.Draw(page, new RectangleF(new PointF(0, 40), new SizeF(graphics.ClientSize.Width, graphics.ClientSize.Height - 100)), layoutFormat);

            //using syncfusion.pdf.net.core
            MemoryStream dataStream = new MemoryStream();
            document.Save(dataStream);
            dataStream.Position = 0;
            filename = filename + DateTime.Now.ToString("yyyyMMddHHmmss") + ".pdf";
            byte[] byteData = dataStream != null ? ConvertStreamToByte(dataStream) : null;
            string byteString = byteData != null ? Convert.ToBase64String(byteData) : null;
            return new JsonResult(new { filename = filename, bytes = byteString, fileType = "application/pdf" });
        }

Put below code in Controller

[HttpPost]
        public IActionResult ExportDataToPdf(YourViewModel request)
        {
            var response = _repo.GetData(request);
            if (response != null)
            {
               
                string fileName = "pdfReport";
                //Export to excel
                return _repo.ExportToPDF(response, fileName);
            }
            else
            {
                return null;
            }
        }

JavaScript Code

function ExportToPDF() {

    var request = {
        FromDate: $("#dtFromDate").val(),
        ToDate: $("#dtToDate").val()
    }

    $.ajax({
        type: 'POST',
        url: "/YourController/ExportDataToPdf",
        data: request,
        //contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (r) {
            var blob = new Blob([Base64ToBytes(r.bytes)], { type: r.fileType });
            var link = document.createElement('a');
            link.href = window.URL.createObjectURL(blob);
            var fileName = r.filename;
            link.download = fileName;
            link.click();
            URL.revokeObjectURL(link.href);
        },
        error: function (err) {
            console.log(err)
        }
    });

}

function Base64ToBytes(base64) {
    return Uint8Array.from(atob(base64), c => c.charCodeAt(0));
};

Finally you can attach id to an element in html and in JavaScript on Document ready method you can give call to ExportToPDF() and you are done

Leave a Reply

Your email address will not be published.