0
votes

I am creating table and adding cells to table with text or image content.

var  pdfTable = new PdfPTable(2);
                nCell = new PdfPCell(new Phrase("A")) {HorizontalAlignment = 1};
                pdfTable.AddCell(nCell);
                pdfTable.AddCell("B");
                pdfTable.AddCell(qrImg);
                pdfTable.AddCell(image39);
                pdfTable.AddCell("C");
                pdfTable.AddCell("D");
                pdfTable.SpacingBefore = 20f;
                pdfTable.SpacingAfter = 30f;
                document.Add(pdfTable);

renders 3 rows and displays image in row2

if I add cells by creating pdfpcell object first:

 var cell = new PdfPCell(qrImg};
 pdfTable.AddCell(nCell);

only rows 1 and 3 are visible.

If I add height property to cell then the image gets diaplayed.

my questions ( 3 but related); is it required for us to specify height when adding cell with image ( cells added with text content - phrase resenders correctly) ? Is there something I am missing when creating a new cell, which prevents images to be rendered? should I always be using Addcell(image) when adding image content?

Thank you all, Mar

1

1 Answers

0
votes

Its easier to understand what's going on if you browse the source. A table within iText keeps a property around called DefaultCell that gets reused over and over. This is done so that the basic cell properties are kept from cell to cell. When you call AddCell(Image) the DefaultCell's image is set to the image, then added to the table, and finally the image get's null'd out.

543     defaultCell.Image = image;
544     AddCell(defaultCell);
545     defaultCell.Image = null;

The PdfCell(Image) constructor actually internally calls an overload PdfPCell(Image, bool) and passes false as the second parameter, fit. Here's the constructor's conditional on fit:

152     if (fit) {
153         this.image = image;
154         Padding = borderWidth / 2;
155     }
156     else {
157         column.AddText(this.phrase = new Phrase(new Chunk(image, 0, 0, true)));
158         Padding = 0;
159     }

If you pass false to fit, which is the default, you'll see that the image is added in a much more complicated way.

So basically you can add an image in three main ways (okay, lots more actually if you use nested tables or chunks or phrases), the first below picks up the defaults and is probably what you want. The second is more raw but gets you closer to what you probably want. The third is the most raw and assumes that you know what you're doing.

var qrImg = iTextSharp.text.Image.GetInstance(sampleImage1);

//Use the DefaultCell, including any existing borders and padding
pdfTable.AddCell(qrImg);

//Brand new cell, includes some padding to get the image to fit
pdfTable.AddCell(new PdfPCell(qrImg, true));

//Brand new cell, image added as a Chunk within a Phrase
pdfTable.AddCell(new PdfPCell(qrImg));