Example of RadGrid sent as Email Attachment in PDF or Excel

6 posts, 0 answers
  1. Mike
    Mike avatar
    338 posts
    Member since:
    Jun 2008

    Posted 29 May 2013 Link to this post

    Here is some code that I whpped together which shows how to create a pdf or xls document from a RadGrid and  attach it to an email.

    I only had time to draft the basics, but you should get the idea and I thought that I would share since members like Princy helped me get here.
    <telerik:RadGrid ID="RadGrid1"  
                   AllowSorting="false"
                   AutoGenerateColumns="false"
                   AlternatingItemStyle-HorizontalAlign="center"
                   AlternatingItemStyle-BackColor="#ffffff"               
                   GroupingEnabled="true"
                   OnExcelExportCellFormatting="RadGrid1_ExcelExportCellFormatting"
                   OnGridExporting="RadGrid1_GridExporting"
                   OnPdfExporting="RadGrid1_PdfExporting"
                   ExportSettings-Excel-Format="Html"
                   ExportSettings-ExportOnlyData="true"
                   Width="100%"
                   runat="server">  
                   <MasterTableView  Width="99%">                
                   <Columns>  ...

    using System;
    using System.Collections.Generic;
    using System.Configuration;
    using System.Data;
    using System.IO;
    using System.Net;
    using System.Net.Mail;
    using System.Text;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using Mec.CommonLibrary.Cryptography;
    using MEC.EMA.BLL;
    using Microsoft.Security.Application;
    using Telerik.Web.UI;
     
     
    public class EmailRadGridAttachment
    {
     
        List<Person> _userList = new List<Person>();
        UserBLL _userBLL = new UserBLL();
     
        protected void Page_Load(object sender, EventArgs e)
        {
            BindGrid();
        }
     
        protected void BindGrid()
        {
            _userList = _userListBLL.GetUserById(_userId);
            RadGrid1.DataSource = _userList;
        }
     
        // aspx page with a button that fires this event for Excel
        protected void ButtonExcel_Click(object sender, EventArgs e)
        {
            ConfigureExport();
            RadGrid Grid1 = (RadGrid)Page.Master.FindControl("Main").FindControl("RadGrid1");
            Grid1.MasterTableView.ExportToExcel();
        }
     
        // aspx page with a button that fires this even for PDF
        protected void ButtonPdf_Click(object sender, System.EventArgs e)
        {
            ConfigureExport();
            RadGrid Grid1 = (RadGrid)Page.Master.FindControl("Main").FindControl("RadGrid1");
            Grid1.ExportSettings.Pdf.AllowPrinting = true;
            Grid1.ExportSettings.Pdf.AllowModify = true;
            Grid1.ExportSettings.Pdf.AllowCopy = true;
            Grid1.ExportSettings.Pdf.AllowAdd = true;
            // I found that if I don't use postscript fonts the data does not make it to the attachment
            Grid1.ExportSettings.Pdf.DefaultFontFamily = "Helvetica";
            Grid1.ExportSettings.Pdf.PageLeftMargin = new Unit(2, UnitType.Mm);
            Grid1.ExportSettings.Pdf.PageRightMargin = new Unit(2, UnitType.Mm);
            Grid1.ExportSettings.Pdf.PageHeaderMargin = new Unit(0, UnitType.Mm);
            Grid1.ExportSettings.Pdf.PaperSize = GridPaperSize.Legal;
            // to get lanscape orientation     
            Grid1.ExportSettings.Pdf.PageHeight = Unit.Parse("210mm");
            // Width based on TOU and NON-TOU Columns and the smaller parse the more room for data
            Grid1.ExportSettings.Pdf.PageWidth = Unit.Parse("420mm");
     
            foreach (GridColumn col in RadGrid1.MasterTableView.RenderColumns)
            {
                // We have the ability to control the width of columns in the export here
                if (col.UniqueName != "MiddleInitial")
                {
                    col.HeaderStyle.Width = Unit.Pixel(50);
                }
            }
            Grid1.MasterTableView.ExportToPdf();
        }
     
        protected void RadGrid1_PdfExporting(object sender, GridPdfExportingArgs e)
        {
            // I have added some more information that will be included in the PDF above the RadGrid here
            StringBuilder customHTML = new StringBuilder();
            customHTML.Append("<p style='color: red; font-weight: bold; font-size: 10pt;'>Title Page</p>");
            customHTML.Append("<table style='font-family:Helvetica;font-size:9pt;width:500px;'>");
            // Very Important to make sure you have a colgroup and the same number of "<col>" as "<td>"
            customHTML.Append("<colgroup><col style='width: 200px; white-space:nowrap;' /><col style='text-align:left;' /></colgroup>");
            // ColGroup = Number of <td> in a row is needed for Telerik export to PDF
            customHTML.Append("<tr><td>Customer: " + CustomerName.Text + "</td><td>Date: " + LabelDate.Text + " </td></tr>");
            customHTML.Append("<tr><td>Address: " + LabelAddress.Text + "</td><td>Email: " + LabelEmail.Text + " </td></tr>");
            customHTML.Append("<tr><td>City: " + LabelCity.Text + "</td><td>Phone: " + LabelPhone.Text + " </td></tr>");
            customHTML.Append("<tr><td>State: " + LabelState.Text + "</td><td>Zip: " + LabelZipCode.Text + " </td></tr>");
            customHTML.Append("</table>");      
            e.RawHTML = customHTML + e.RawHTML;
        }
           
     
       
     
        public void ConfigureExport()
        {
            RadGrid Grid1 = (RadGrid)Page.Master.FindControl("Main").FindControl("RadGrid1");
            Grid1.ExportSettings.ExportOnlyData = true;
            Grid1.ExportSettings.IgnorePaging = true;
            // We don't want the Open, Save or Cancel prompt to open for a new window when calling this page
            Grid1.ExportSettings.OpenInNewWindow = false;
        }
     
        protected void RadGrid1_GridExporting(object source, GridExportingArgs e)
        {             
            StringBuilder customHTML = new StringBuilder();
            MemoryStream gridMemoryStream = new MemoryStream(new ASCIIEncoding().GetBytes(e.ExportOutput));
            if (e.ExportType == ExportType.Excel)
            {
                SendEMailWithAttachment(gridMemoryStream, "attachment.xls");          
            }
            // Stuff the Grid in a memory stream and pass it to the email method
            if (e.ExportType == ExportType.Pdf)
            {
                SendEMailWithAttachment(gridMemoryStream, "attachment.pdf");          
            }
            gridMemoryStream.Close();
            // Redirect to the same page so the alert does not pop-up
            Response.Redirect(Request.Url.AbsoluteUri);
        }
     
        public void SendEMailWithAttachment(Stream attachmentStream, string fileName)
        {
            //settings from the web.config
            SmtpClient smtpClient = new SmtpClient(Convert.ToString(ConfigurationManager.AppSettings["SERVER_EMAIL"]));
            string authType = "Basic";
            MailMessage email = new MailMessage();
            StringBuilder body = new StringBuilder();
            string emaURL = Convert.ToString(ConfigurationManager.AppSettings["BASE_URL"]);
            email.From = new MailAddress("From@gmail.com");
            email.To.Add("To@gmail.com");
            email.Subject = "This is the subject";
            body.Append("<table style='font-family:Helvetica;font-size:9pt;width:600px;'>");
            body.Append("<tr><td>You can put in whatever you want here</td></tr>");
            body.Append("</table>");
            // Attachment goes here
            email.Attachments.Add(new Attachment(attachmentStream, fileName));
            email.Body = body.ToString();
            email.IsBodyHtml = true;
            NetworkCredential nc = new NetworkCredential(Convert.ToString(ConfigurationManager.AppSettings["CredentialU"]), Convert.ToString(ConfigurationManager.AppSettings["CredentialP"]));
            smtpClient.Credentials = nc.GetCredential(Convert.ToString(smtpClient), 25, authType);
            smtpClient.Send(email);
        }
    }

  2. Neha
    Neha avatar
    6 posts
    Member since:
    Feb 2013

    Posted 19 Sep 2015 in reply to Mike Link to this post

    Hi Mike,

     I am using this approach for my project. Everything is working fine but _pdfexporting event, the GridPdfExportingargs.RawHTML is adding duplicate columns.

     I have 3 columns for my grid and when I reach this event, the e.RawHtml shows 6 columns.

    Following is the code:

     

    Protected Sub grdPDFDetailReports_PdfExporting(ByVal sender As Object, ByVal e As GridPdfExportingArgs)
            ' I have added some more information that will be included in the PDF above the RadGrid here
            Dim customHTML As New StringBuilder()
            Dim facilityDTO As New FacilityDTO

            InnCode = Convert.ToString(Session("Inncode"))
            facilityDTO = SharedMethods.GetFacilityDetailsByInnCode(InnCode)
            brandID = facilityDTO.FacilityBrandFamilyID

            customHTML.Append("<table style='font-family:Helvetica;font-size:15pt;width:2500px;'>")
            ' Very Important to make sure you have a colgroup and the same number of "<col>" as "<td>"
            customHTML.Append("<colgroup><col style='width: 2000px; white-space:nowrap;' /><col style='text-align:center;' /></colgroup>")
            ' ColGroup = Number of <td> in a row is needed for Telerik export to PDF
            customHTML.Append("<tr><td>InnCode: " + "CHICI" + "</td></tr>")
            customHTML.Append("<tr><td>Brand: " + facilityDTO.BrandFamily + "</td></tr>")
            customHTML.Append("<tr><td>Hotel Name: " + facilityDTO.Name + "</td></tr>")
            customHTML.Append("<tr><td>Management Type: " + facilityDTO.ManagementType + "</td></tr>")
            customHTML.Append("<tr><td>State: " + facilityDTO.State + "</td></tr>")
            customHTML.Append("<tr><td>City & Zip: " + facilityDTO.City + " & " + facilityDTO.Zip + "</td></tr>")
            customHTML.Append("</table>")
            e.RawHTML = customHTML.Append(e.RawHTML).ToString

    End Sub

     

    This is my grid aspx:

     <telerik:RadGrid ID="grdPDFDetailReports" runat="server"  Skin="Default" OnPdfExporting="grdPDFDetailReports_PdfExporting" OnGridExporting="grdPDFDetailReports_GridExporting"
    >
            <MasterTableView>
                <Columns>
                  <telerik:GridBoundColumn DataField="Description" HeaderText="Description" ReadOnly="True"
                        SortExpression="Description" HtmlEncode="true">
                    </telerik:GridBoundColumn>
                    <telerik:GridBoundColumn DataField="Type" HeaderText="Type" ReadOnly="True" SortExpression="Type"
                        HtmlEncode="true">
                    </telerik:GridBoundColumn>
                    <telerik:GridBoundColumn DataField="Grade" HeaderText="Grade" ReadOnly="True" SortExpression="Grade"
                        HtmlEncode="true">
                    </telerik:GridBoundColumn>
                    </Columns>
                    </MasterTableView>
                    </telerik:RadGrid>

     

    This is what e.rawHTML shows:

     

    <table rules="all" border="1" id="ctl00_MainContent_grdPDFDetailReports_ctl00" style="width:100%;table-layout:auto;empty-cells:show;">
    <colgroup>
    <col  />
    <col  />
    <col  />
    <col  />
    <col  />
    <col  />
    </colgroup>
    <thead>
    <tr>
    <th scope="col">Description</th><th scope="col">Type</th><th scope="col">Grade</th><th scope="col">Description</th><th scope="col">Type</th><th scope="col">Grade</th>
    </tr>
    </thead><tbody>
    <tr>

    Please suggest how can I remove duplicate columns.​

  3. Neha
    Neha avatar
    6 posts
    Member since:
    Feb 2013

    Posted 19 Sep 2015 in reply to Neha Link to this post

    Hi Mike,

    I have another query. I want to call exporttopdf,  grid_pdfexporting andgrid_gridexporting events in loop but the control comes out after exporttopdf is done and moves for the next item in loop. Is there a way where we can forcefully raise the events.

  4. Kostadin
    Admin
    Kostadin avatar
    1733 posts

    Posted 23 Sep 2015 Link to this post

    Hello Neha,

    I assume the cause for the double columns is that you did not disable the auto generated columns. Please disable the AutoGenerateColumns property and check whether the issue remains.
    <telerik:RadGrid ID="grdPDFDetailReports" runat="server"  Skin="Default" OnPdfExporting="grdPDFDetailReports_PdfExporting" OnGridExporting="grdPDFDetailReports_GridExporting" AutoGenerateColumns="false" >

    Regards your second query I am afraid you cannot fire the events during a single request. That means first will fire OnPdfExporting and then OnGridExporting event will be fire. If you want to execute it again you have to fire ExportToPdf again after this request.

    Regards,
    Kostadin
    Telerik
    Do you want to have your say when we set our development plans? Do you want to know when a feature you care about is added or when a bug fixed? Explore the Telerik Feedback Portal and vote to affect the priority of the items
  5. Elakkiya
    Elakkiya avatar
    1 posts
    Member since:
    Dec 2018

    Posted 26 Dec 2018 in reply to Mike Link to this post

    Hi Mike,

            Export to Excel was working as the expected, but when I click for export to pdf....the  message says " xxxxxxxxx.pdf is Protected. Please Enter a document Open password".I have tried with different passwords and by enabling and disabling the User password in pdf setting. Can you please help me out in this 

  6. Marin Bratanov
    Admin
    Marin Bratanov avatar
    4489 posts

    Posted 28 Dec 2018 Link to this post

    Hi Elakkiya,

    There are no such known issues with the grid PDF export and so I advise that you:

    1. make sure pdf protection/password is not set somewhere in the code-behind of the page as well
    2. upgrade to the latest version (there was an issue with that in 2010, see here for more details)
    3. make sure that the problem does not stem from an Antivirus, the email client or other similar software that may be tampering with the file after it is generated from the grid
    4. if you still can't resolve it, open a support ticket where you can send us an MCVE of the problem so we can help

     


    Regards,
    Marin Bratanov
    Progress Telerik
    Get quickly onboarded and successful with your Telerik and/or Kendo UI products with the Virtual Classroom free technical training, available to all active customers. Learn More.
Back to Top