Search code examples
c#pdf-generationitextitext7

Wrap text around image in cell using iText 7


I have a PDF document with a table. The code is the following:

PdfWriter _writer = new PdfWriter(@"C:\output.pdf");
PdfDocument _document = new PdfDocument(_writer);
Document MyDocument = new Document(_document, PageSize.A4);

Table MyTable = new Table(new float[] { 1, 4 });
MyTable.SetWidthPercent(100);
MyTable.AddHeaderCell(new Cell().Add(new Paragraph("ID")));
MyTable.AddHeaderCell(new Cell().Add(new Paragraph("Description")));

MyTable.AddCell(new Cell().Add(new Paragraph("1")));
Cell descCell = new Cell();
descCell.Add(IMG); // iText.Layout.Element.Image
descCell.Add(new Paragraph("This is the description."));
MyTable.AddCell(descCell);

MyDocument.Add(MyTable);
MyDocument.Close();

Actually the output is this:

enter image description here

What I am trying to achieve is this:

enter image description here

I have read several examples for iText 5 and all point to using this property:

image.setAlignment(Image.LEFT | Image.TEXTWRAP);

The problem is that it doesn't seem to be avaliable on iText 7.

Any help would be appreciated.


Solution

  • Floating elements functionality has been implemented in 7.0.3-SNAPSHOT and is likely to make it into 7.0.3 release.

    In order for the text to wrap around an image in a cell, you would need to specify that an image is a floating element, just like in HTML. To do that, use

    Image img = ...
    img.setProperty(Property.FLOAT, FloatPropertyValue.LEFT);
    

    Then, construct a cell as usual by adding an image and text to it:

    table.addCell(new Cell().add(img).add(textStr);
    

    The output would look like the following:

    enter image description here