This is a migrated thread and some comments may be shown as answers.

Generate pdf from radgrid having images(binary)

3 Answers 156 Views
Data Access Free Edition
This is a migrated thread and some comments may be shown as answers.
This question is locked. New answers and comments are not allowed.
Ankur
Top achievements
Rank 1
Ankur asked on 13 May 2014, 10:28 AM
I have to export to pdf rad grid data having images (which are stored in database in binary format).
My .aspx code is :

<Columns>
                            <telerik:GridBoundColumn DataField="ItemID" DataType="System.Int32" ReadOnly="True"
                                SortExpression="ItemID" UniqueName="ItemID" HeaderText="Menu &#8470;">
                            </telerik:GridBoundColumn>

                            <telerik:GridTemplateColumn HeaderText="Image" SortExpression="ItemID" UniqueName="Image">
                                <ItemTemplate>
                                    <asp:Image ID="SushiImage" runat="server" ImageUrl='<%#"MyHandler.ashx?FileGUID=" + DataBinder.Eval(Container.DataItem, "FileGUID")%>'
                                        AlternateText="Sushi image" Width="100px" Height="75px" Style="border: 1px solid #000000;"></asp:Image>
                                </ItemTemplate>
                            </telerik:GridTemplateColumn>
                        </Columns>

and cs code is:
onload:
  RadGrid1.DataSource = GetImages("select top 10 FileGUID,ImageFile,ItemID from tbl_ImageFiles");
            RadGrid1.DataBind();
onexportPDF click:

isPdfExport = true;
            RadGrid1.MasterTableView.ExportToPdf();

image format in db is:
fileguid=5858A322-E74F-4946-BEE6-B00479384BB8,image file="0xFFD8FFE000104A464946000102010060006......"
filetype=".jpg", filename="", id="".

So can any one please help me to resolve my problem.

3 Answers, 1 is accepted

Sort by
0
Kristian Nikolov
Telerik team
answered on 14 May 2014, 11:35 AM
Hello Ankur,

In order to help you resolve your situation we would need some additional details regarding the nature of the problem you are facing. Therefore we kindly ask you to provide us with the following information:
  1. What is the exact issue you are having - are you experiencing an error or are you unable to retrieve the binary data from the database? Please describe your situation.
  2. Are you using Telerik Data Access to access the database from your application?
  3. Please send us the code of the GetImages method along with the code of any other relevant methods called from withing GetImages.
This should help us gain better understanding of your scenario.

We are looking forward to your feedback.

Regards,
Kristian Nikolov
Telerik
 
OpenAccess ORM is now Telerik Data Access. For more information on the new names, please, check out the Telerik Product Map.
 
0
Ankur
Top achievements
Rank 1
answered on 14 May 2014, 01:00 PM
my .aspx code is :

 <asp:ImageButton ID="DownloadPDF" runat="server" OnClick="DownloadPDF_Click" ImageUrl="~/Images/heroAccent.png"
        CssClass="pdfButton"></asp:ImageButton>

<telerik:RadGrid ID="RadGrid1" runat="server" GridLines="None"
                    AllowSorting="true" Skin="Black" Width="745px" AllowPaging="True"
                    AutoGenerateColumns="False">
                    <ExportSettings IgnorePaging="true" OpenInNewWindow="true">
                        <Pdf PageHeight="210mm" PageWidth="297mm" DefaultFontFamily="Arial Unicode MS" PageTopMargin="45mm"
                            BorderStyle="Medium" BorderColor="#666666">
                        </Pdf>
                    </ExportSettings>
                    <MasterTableView CommandItemDisplay="Top" DataKeyNames="ItemID"
                        PageSize="4" TableLayout="Fixed">
                        <PagerStyle Mode="NumericPages"></PagerStyle>
                     
                        <Columns>
                            <telerik:GridBoundColumn DataField="ItemID" DataType="System.Int32" ReadOnly="True"
                                SortExpression="ItemID" UniqueName="ItemID" HeaderText="Menu &#8470;">
                            </telerik:GridBoundColumn>

                            <telerik:GridTemplateColumn HeaderText="Image" SortExpression="ItemID" UniqueName="Image">
                                <ItemTemplate>
                                   
<asp:Image ID="SushiImage" runat="server"
ImageUrl='<%#"MyHandler.ashx?FileGUID=" +
DataBinder.Eval(Container.DataItem, "FileGUID")%>'
                                       
AlternateText="Sushi image" Width="100px" Height="75px" Style="border:
1px solid #000000;"></asp:Image>
                                </ItemTemplate>
                            </telerik:GridTemplateColumn>
                        </Columns>
                    </MasterTableView>
                    <HeaderStyle HorizontalAlign="Center" Font-Size="16px"></HeaderStyle>
                    <ItemStyle HorizontalAlign="Center" Font-Names="Arial Unicode MS" Font-Size="16px"
                        ForeColor="#eeeeee"></ItemStyle>
                    <AlternatingItemStyle HorizontalAlign="Center" Font-Names="Arial Unicode MS" Font-Size="16px"
                        ForeColor="#eeeeee"></AlternatingItemStyle>
                </telerik:RadGrid>


and .cs code is :
====onpageload====
RadGrid1.DataSource = GetImages("select top 10 FileGUID,ImageFile,ItemID from tbl_ImageFiles");
            RadGrid1.DataBind();
==
protected void RadGrid1_ItemCreated(object sender, GridItemEventArgs e)
        {

            if (isPdfExport)
                FormatGridItem(e.Item);
        }
===
protected void DownloadPDF_Click(object sender, EventArgs e)
{
 isPdfExport = true;
            RadGrid1.MasterTableView.ExportToPdf();
}
====
public DataSet GetImages(string sqlquery)
        {
            SqlConnection con = new SqlConnection(@"Data Source=;Initial Catalog=;User Id=; Password=;");
            SqlDataAdapter cmd = new SqlDataAdapter(sqlquery, con);
            con.Open();
            DataSet ds = new DataSet();
            cmd.Fill(ds);
            con.Close();
            return ds;
        }
===
and MyHandler.ashx code is:

public void ProcessRequest(HttpContext context)
        {
            if (context.Request.QueryString["FileGUID"].ToString() != "")
            {
                SqlConnection objSqlCon = new SqlConnection(db.ConnectionString);
                objSqlCon.Open();
                SqlTransaction objSqlTran = objSqlCon.BeginTransaction();

                SqlCommand objSqlCmd = new SqlCommand("up_GetImageFile", objSqlCon, objSqlTran);
                objSqlCmd.CommandType = CommandType.StoredProcedure;

                SqlParameter objSqlParam1 = new SqlParameter("@FileGUID", SqlDbType.VarChar);

                objSqlParam1.Value = context.Request.QueryString["FileGUID"].ToString();

                objSqlCmd.Parameters.Add(objSqlParam1);
                string path = string.Empty;
                string FileType = string.Empty;
                string FormName = string.Empty;

                using (SqlDataReader sdr = objSqlCmd.ExecuteReader())
                {
                    while (sdr.Read())
                    {
                        path = sdr[0].ToString();
                        FileType = sdr[1].ToString();
                        FormName = sdr[2].ToString();
                    }

                }

                objSqlCmd = new SqlCommand("SELECT GET_FILESTREAM_TRANSACTION_CONTEXT()", objSqlCon, objSqlTran);

                byte[] objContext = (byte[])objSqlCmd.ExecuteScalar();
                if (path != "")
                {

                    SqlFileStream objSqlFileStream = new SqlFileStream(path, objContext, FileAccess.Read);

                    byte[] buffer = new byte[(int)objSqlFileStream.Length];
                    objSqlFileStream.Read(buffer, 0, buffer.Length);
                    objSqlFileStream.Close();

                    objSqlTran.Commit();

                   
HttpContext.Current.Response.AddHeader("Content-disposition",
"attachment; filename=" + Path.GetFileName(FormName) + FileType);
                    // Here you need to manage the download file stuff according to your need
                    HttpContext.Current.Response.ContentType = "application/octet-stream";

                    HttpContext.Current.Response.BinaryWrite(buffer);
                    HttpContext.Current.Response.End();
                }
            }
        }
====
database column :
FileGUID(uniqueidentifier),image file(varbinary max),filetype ,filename and itemid.

=====and on page load i had bind the grid with image but when i click on DownloadPDF_Click button i am geting exception :

System.ArgumentException: Illegal characters in path.
  at System.IO.Path.CheckInvalidPathChars(String path, Boolean checkAdditional)
  at System.Security.Permissions.FileIOPermission.CheckIllegalCharacters(String[] str)

  at
System.Security.Permissions.FileIOPermission.AddPathList(FileIOPermissionAccess
access, AccessControlActions control, String[] pathListOrig, Boolean
checkForDuplicates, Boolean needFullPath, Boolean copyPathList)
  at System.Security.Permissions.FileIOPermission..ctor(FileIOPermissionAccess access, String path)
  at System.Web.InternalSecurityPermissions.PathDiscovery(String path)
  at System.Web.HttpRequest.MapPath(VirtualPath virtualPath, VirtualPath baseVirtualDir, Boolean allowCrossAppMapping)
  at System.Web.HttpServerUtility.MapPath(String path)
  at Telerik.Web.Apoc.Image.ApocImageFactory.TryMapPath(String path, String& physPath)
  at Telerik.Web.Apoc.Image.ApocImageFactory.Make(String href)
  at Telerik.Web.Apoc.Fo.Flow.ExternalGraphic.Layout(Area area)
  at Telerik.Web.Apoc.Fo.Flow.Block.Layout(Area area)
  at Telerik.Web.Apoc.Fo.Flow.TableCell.Layout(Area area)
  at Telerik.Web.Apoc.Fo.Flow.TableRow.Layout(Area area)
  at Telerik.Web.Apoc.Fo.Flow.AbstractTableBody.Layout(Area area)
  at Telerik.Web.Apoc.Fo.Flow.Table.Layout(Area area)
  at Telerik.Web.Apoc.Fo.Flow.Block.Layout(Area area)
  at Telerik.Web.Apoc.Fo.Flow.Flow.Layout(Area area, Region region)
  at Telerik.Web.Apoc.Fo.Flow.Flow.Layout(Area area)
  at Telerik.Web.Apoc.Fo.Pagination.PageSequence.Format(AreaTree areaTree)
  at Telerik.Web.Apoc.StreamRenderer.Render(PageSequence pageSequence)
  at Telerik.Web.Apoc.Fo.FOTreeBuilder.EndElement()
  at Telerik.Web.Apoc.Fo.FOTreeBuilder.Parse(XmlReader reader)
0
Kostadin
Telerik team
answered on 19 May 2014, 08:17 AM
Hello Ankur,

Note that we strongly recommend to use advanced data-binding when perform complex operations such as exporting the grid. Additionally keep in mind that our PDF engine can export all images nevertheless whether they use an absolute or relative path, but binary image will not be exported. If you try to export a binary image the export document will be created but it will not contains the image.

Regards,
Kostadin
Telerik
 

Check out the Telerik Platform - the only platform that combines a rich set of UI tools with powerful cloud services to develop web, hybrid and native mobile apps.

 
Tags
Data Access Free Edition
Asked by
Ankur
Top achievements
Rank 1
Answers by
Kristian Nikolov
Telerik team
Ankur
Top achievements
Rank 1
Kostadin
Telerik team
Share this question
or