How to add an image to a table cell in iTextSharp using webmatrix

◇◆丶佛笑我妖孽 提交于 2019-12-02 10:11:26

问题


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"


来源:https://stackoverflow.com/questions/16589044/how-to-add-an-image-to-a-table-cell-in-itextsharp-using-webmatrix

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!