I am trying to create a PDF report from data. One of the columns contains an image. How can I extract an image from a datatable and paste into a pdf table? I am using iTextShap version 5.4.2.0. Here is the code:
public void Report(DataTable dt, string output) { Document doc = new Document(PageSize.LETTER, 50, 50, 80, 50); PdfWriter PDFWriter = PdfWriter.GetInstance(doc, new FileStream(output, FileMode.Create)); PDFWriter.ViewerPreferences = PdfWriter.PageModeUseOutlines; iTextSharp.text.Font hel8 = FontFactory.GetFont(BaseFont.HELVETICA, 8); doc.Open(); PdfPTable table = new PdfPTable(dt.Columns.Count); float[] widths = new float[] { 1.2f, 1.2f, 1.2f, 1.2f, 1f, 4f, 1f, 4f }; table.SetWidths(widths); table.WidthPercentage = 100; PdfPCell cell = new PdfPCell(new Phrase("NewCells")); cell.Colspan = dt.Columns.Count; foreach (DataColumn c in dt.Columns) { table.AddCell(new Phrase(c.ColumnName, hel8)); } foreach (DataRow r in dt.Rows) { if (dt.Rows.Count > 0) { table.AddCell(new Phrase(r[0].ToString(), hel8)); table.AddCell(new Phrase(r[1].ToString(), hel8)); table.AddCell(new Phrase(r[2].ToString(), hel8)); table.AddCell(new Phrase(r[3].ToString(), hel8)); table.AddCell(new Phrase(r[4].ToString(), hel8)); table.AddCell(new Phrase(r[5].ToString(), hel8)); byte[] byt = (byte[])r[6]; MemoryStream ms = new MemoryStream(byt); System.Drwaing.Image sdi = System.Drawing.Image.FromStream(ms); Image img = Image.GetInstance(sdi); <-- this is the problem code table.AddCell(img); table.AddCell(new Phrase(r[7].ToString(), hel8)); } } doc.Add(table); } doc.Close(); }
Update: @nekno, all your suggestions work.
But I still need to fix the cast in the line:
byte[] byt = (byte[])r[6];
This gave me an exception for an exception from VS2008. So I added a conversion function (pulled it from stackoverflow):
byte[] ImageToByte(System.Drawing.Image img) { byte[] byteArray = new byte[0]; using (MemoryStream stream = new MemoryStream()) { img.Save(stream, System.Drawing.Imaging.ImageFormat.Png); stream.Close(); byteArray = stream.ToArray(); } return byteArray; }
And changed the code:
byte[] byt = ImageToByte((System.Drawing.Image)dt.Rows[e][6]);
Thanks.