ITextSharp:文本没有环绕单元格中的图像

时间:2012-05-23 12:37:30

标签: c# image pdf itextsharp

我遇到了真正的问题,我有一个带有短语的单元格,我想在短语的左边有一个小图标,但每个元素都在新行上呈现

这是我的代码返回单元格:

var cell = new PdfPCell();
Bitmap bitmap = new Bitmap(21, 21);
Graphics g = Graphics.FromImage(bitmap);

g.Clear(Color.White);

SolidBrush brush = new SolidBrush(colour);
g.FillEllipse(brush, 0, 0, 20, 20);
brush.Dispose();

g.DrawImageUnscaled(bitmap, 0, 0);

g.Dispose();

var imgIcon = iTextSharp.text.Image.GetInstance(bitmap, System.Drawing.Imaging.ImageFormat.Jpeg);
bitmap.Dispose();
//imgIcon.Alignment = iTextSharp.text.Image.TEXTWRAP | iTextSharp.text.Image.ALIGN_RIGHT;
cell.AddElement(imgIcon);

var phrase = new Phrase(o.ToString(), Report.Fonts.Table);
cell.AddElement(phrase);

//this code scales the image so that it does not fit the cell
foreach (IElement element in cell.CompositeElements)
{
     PdfPTable tblImg = element as PdfPTable;
     if (tblImg != null)
     {
         tblImg.TotalWidth = 10;
         tblImg.LockedWidth = true;
     }
}
return cell;

这是输出:

enter image description here

任何帮助将不胜感激

- 编辑: 这是imgIcon的alignment属性集

的输出

enter image description here

2 个答案:

答案 0 :(得分:3)

iTextSharp Image对象显示为元素(以CSS术语表示)。您需要在Image中明确包装Chunk以获取内嵌显示,如下所示:

PdfPTable table = new PdfPTable(1) {
  TotalWidth = 100, LockedWidth = true, 
  HorizontalAlignment = Element.ALIGN_LEFT
};
PdfPCell cell = new PdfPCell();
Phrase p = new Phrase(new Chunk(image, 0, 0));
p.Add(new Phrase("Print"));
cell.AddElement(p);
table.AddCell(cell);

cell = new PdfPCell();
p = new Phrase(new Chunk(image, 0, 0));
p.Add(new Phrase("A long phrase that will make the PdfPCell wrap it's containing text."));
cell.AddElement(p);
table.AddCell(cell);
document.Add(table);

代码段结果:

Code snippet result

答案 1 :(得分:0)

我认为这个答案:

Image alignment in text?

可能有答案。您需要设置图像的对齐方式:

....
imgIcon.Alignment = 6;
cell.AddElement(imgIcon);
....