Image auto resizes in PdfPCell with iTextSharp

I'm using iTextSharp v4.1.2 and I get the following behavior:

Using this code, adding the image directly to the table via the AddCell method, the image is scaled up to fit the cell:

nestedTable.AddCell(image);

Using this code, adding the image to a cell, then adding the cell to the table, the image is displayed at its original size:

PdfPCell cell = new PdfPCell(image);
cell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
nestedTable.AddCell(cell);



Have you added the image directly to the pdf document (outside the table) just to compare/double-check the image sizes?

document.add(image);



I assume that you want the image centered in the cell with some space around it. As a last resort, you can change your image. Make it a png with a transparent background, and just make sure that there is some transparent 'margin' around all the edges of your image.

EDIT

I just downloaded the v5.0.2 and I get the same results as mentioned above. I've tried it with images that are both smaller and larger than the size of the cell, and the behavior is the same; the first method scales the image, the second method does not.

EDIT

Well, apparently I have been wrong for years about the whole DPI thing when it comes to images. I can't seem to see that it makes any difference at all what the DPI of the image is.
I created a 600x400px image at three different resolutions, 72dpi, 96 dpi, and 110 dpi. Then I added each these images to a new document that was exactly 600x400.

Dim pSize As Rectangle = New Rectangle(600, 1000)
Dim document As Document = New Document(pSize, 0, 0, 0, 0)

For each of the three image files, when added to the document with

document.add(image)

they fit the document perfectly, with no differences for the different DPI settings.


@Stewbob's answer does work, but it's only incidently related to the methods of the table.

The thing with iTextSharp is that it will behave differently depending on which constructor you use. This will (annoyingly) scale up the image to fill the cell:

PdfPCell c = new PdfPCell();
c.Add(image);
c.setHorizontalAlignment(Element.ALIGN_CENTER); // this will be ignored

But this will leave the image at the size you set it (and allow for alignment):

PdfPCell c = new PdfPCell(image);  
c.setHorizontalAlignment(Element.ALIGN_CENTER);

I don't know exactly why this is, it's got something to do with the cell being in 'text mode' if you add the image in the constructor versus 'composite mode' if you add it later (in which case each object is supposed to look after it's own alignment).

Some more info (in Java, but still applies) http://tutorials.jenkov.com/java-itext/table.html#cell-modes