Putting several images next to each other in a pdfcell with itextsharp

孤街浪徒 提交于 2019-12-22 13:53:34

问题


I'm using itextsharp with a aspmvc project to create PDF versions of some of my pages. I have a very basic parser which takes simple html (plus some style info supplied seperately) and creates a pdf. When my parser encounts a table it loops over rows then cells, creating a PdfPCell for each cell. It then loops over child elements of the cell adding them to the PdfPCell. It's pretty basic but it's worked for me so far.

The problem is that I now have a table one column of which contains a number of icons, indicating different status for the row. When these images get added then end up one above the other in the pdf, instead of next to each other.

I create the image with

Dim I As iTextSharp.text.Image = Image.GetInstance(HttpContext.Current.Server.MapPath(El.Attributes("src").InnerText))

I have tried

I.Alignment = Image.TEXTWRAP Or Image.ALIGN_LEFT Or Image.ALIGN_MIDDLE

and adding a text chunk afterwards containing a space but it doesn't help. The only suggestion I have seen is to use I.SetAbsolutePosition(). I'd rather avoid absolute position but am prepared to try it - except I can't work out how to find the current X position to use?

Any help much appreciated.

Adam


回答1:


To get the proper side-by-side flow, wrap the images/text in a Paragraph object, adding them one by one using Chunk and Phrase objects. Something (sorry, I don't do VB) like this:

PdfPTable table = new PdfPTable(2);
PdfPCell cell = new PdfPCell();
Paragraph p = new Paragraph();
p.Add(new Phrase("Test "));
p.Add(new Chunk(image, 0, 0));
p.Add(new Phrase(" more text "));
p.Add(new Chunk(image, 0, 0));
p.Add(new Chunk(image, 0, 0));
p.Add(new Phrase(" end."));
cell.AddElement(p);
table.AddCell(cell);
table.AddCell(new PdfPCell(new Phrase("test 2")));
document.Add(table);

EDIT: One way to add whitespace between the images. Will only work with images; if you try this with mixed text/image(s), they will overlap:

PdfPTable table = new PdfPTable(2);
PdfPCell cell = new PdfPCell();
Paragraph p = new Paragraph();
float offset = 20;
for (int i = 0; i < 4; ++i) {
  p.Add(new Chunk(image, offset * i, 0));
}
cell.AddElement(p);
table.AddCell(cell);
table.AddCell(new PdfPCell(new Phrase("cell 2")));
document.Add(table);

See the Chunk documentation.



来源:https://stackoverflow.com/questions/8485600/putting-several-images-next-to-each-other-in-a-pdfcell-with-itextsharp

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