How to add an image to a table cell in iTextSharp

2019-02-27 22:24发布

问题:

I have made a table with cells and interested in having an image in one of the cell. Below is my code:

doc.Open();
PdfPTable table = new PdfPTable(2);
table.TotalWidth = 570f;
table.LockedWidth = true;
table.HorizontalAlignment = 1; //0=Left, 1=Centre, 2=Right

PdfPCell points = new PdfPCell(new Phrase("and is therefore entitled to 2 points", arialCertify));
points.Colspan = 2;
points.Border = 0;
points.PaddingTop = 40f;
points.HorizontalAlignment = 1;//0=Left, 1=Centre, 2=Right
table.AddCell(points);

 // add a image



doc.Add(table);
Image jpg = Image.GetInstance(imagepath + "/logo.jpg");
doc.Add(jpg);

With the above code, the image shows in my pdf but I want it to be inside a cell so that I can add more cells to the right of the image.

回答1:

On the very basic level you can simply add the image to a PdfPCell and add this cell to your table.

So using your code...

PdfPCell points = new PdfPCell(new Phrase("and is therefore entitled to 2 points", arialCertify));
points.Colspan = 2;
points.Border = 0;
points.PaddingTop = 40f;
points.HorizontalAlignment = 1;//0=Left, 1=Centre, 2=Right

 // add a image
iTextSharp.text.Image jpg = iTextSharp.text.Image.GetInstance(imagepath + "/logo.jpg");
PdfPCell imageCell = new PdfPCell(jpg);
imageCell.Colspan = 2; // either 1 if you need to insert one cell
imageCell.Border = 0;
imageCell.setHorizontalAlignment(Element.ALIGN_CENTER);


table.AddCell(points);
 // add a image
table.AddCell(imageCell);

doc.Add(table);

Update

Check your imagepath. This should be an absolute path to the image, and not relative like in a website page. Also, change your `/logo.jpg' to '\logo.jpg'

this is assuming imagepath is actually to the directory, and not the actual image...

I.E

Server.MapPath(imagepath) + "\\logo.jpg"