User805
User805

Reputation: 123

Export Gridview to PDF with Images with Cellwidth

In my application, I am exporting data from gridview to PDF with images. With the below code, I am exporting text only. How can I export data with images?

Here is the code I used for exporting to pdf:

gvDetails.DataSource = dt1;
gvDetails.DataBind();

int colCount = gvDetails.Columns.Count ;

PdfPTable  table = new PdfPTable(colCount);
table.HorizontalAlignment = 0;
table.WidthPercentage = 100;
int[] colWidths = new int[gvDetails.Columns.Count];
PdfPCell cell;
string cellText;
table.SetWidths(new int[] { 10, 05, 05, 05, 05, 25, 05,40 });
Document pdfDoc = new Document(iTextSharp.text.PageSize.A1, 3, 3, 10, 10);
pdfDoc.Open();
MemoryStream  mem = new MemoryStream();
PdfWriter pdf = PdfWriter.GetInstance(pdfDoc, mem);

for (int colIndex = 0; colIndex < gvDetails.Columns.Count; colIndex++)
{                
    cellText = Server.HtmlDecode(gvDetails.HeaderRow.Cells[colIndex].Text);
    BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA,BaseFont.CP1252,BaseFont.EMBEDDED);
    iTextSharp.text.Font font = new iTextSharp.text.Font(bf, 10, iTextSharp.text.Font.BOLD, iTextSharp.text.Color.WHITE);
    cell = new PdfPCell(new Phrase(cellText.Replace("<br />", Environment.NewLine), font));
    pdfDoc.Open();
    cell.HorizontalAlignment = Element.ALIGN_CENTER;
    cell.VerticalAlignment = Element.ALIGN_MIDDLE;
    cell.FixedHeight = 45f;
    cell.BackgroundColor = new iTextSharp.text.Color(System.Drawing.ColorTranslator.FromHtml("#a52a2a"));
    table.AddCell(cell);
}

for (int rowIndex =0 ; rowIndex < gvDetails.Rows.Count; rowIndex++)
{
    if (gvDetails.Rows[rowIndex].RowType == DataControlRowType.DataRow)
    {
        for (int j = 0; j < gvDetails.Columns.Count - 1; j++)
        {
             cellText = Server.HtmlDecode(gvDetails.Rows[rowIndex].Cells[j].Text);
             cell = new PdfPCell(new Phrase(cellText, FontFactory.GetFont("PrepareForExport", 8)));
             cell.HorizontalAlignment = Element.ALIGN_CENTER;
             cell.VerticalAlignment = Element.ALIGN_MIDDLE;
             cell.FixedHeight = 25f;
             table.AddCell(cell);
        }
    }
}
pdfDoc.Add(table);
pdfDoc.Close();
Response.ContentType = "application/pdf";
Response.AddHeader("Content-Disposition", "attachment;filename=test.pdf");
Response.BinaryWrite(mem.ToArray());
Response.Flush();
Response.End();

Upvotes: 1

Views: 1097

Answers (1)

Chris Haas
Chris Haas

Reputation: 55427

Depending on what you have for an image you can retrieve by using one of the overloads Image.GetInstance():

var img1 = iTextSharp.text.Image.GetInstance("c:\\img.png");
var img2 = iTextSharp.text.Image.GetInstance(new Uri("http://www.example.com/img.png"));

Then just add it to your cell:

cell.AddElement(img1);

Upvotes: 2

Related Questions