6

I am creating a single pdf page with 6 images in a table in separate cells, even though I am setting the images height and width on the server side exactly the same with ScaleToFit the images sizes are not the same on the pdf page.

Is there anyway to get all the images the exact same size?

PdfPTable table = new PdfPTable(3);
table.HorizontalAlignment = Element.ALIGN_CENTER;
table.WidthPercentage = 100;
table.TotalWidth = 698.5f;
table.LockedWidth = true;
table.SetWidths(new float [] {1,1,1});
iTextSharp.text.Image img1 =    iTextSharp.text.Image.GetInstance("C:\\Users\\DaNet\\Downloads\\image.jpg");
img1.Alignment = iTextSharp.text.Image.ALIGN_CENTER;
img1.ScaleToFit(120f, 155.25f);

iTextSharp.text.pdf.PdfPCell imgCell1 = new iTextSharp.text.pdf.PdfPCell(img1);
imgCell1.HorizontalAlignment = Element.ALIGN_CENTER;
imgCell1.BackgroundColor = new BaseColor(255, 255, 255);
imgCell1.Border = iTextSharp.text.Rectangle.NO_BORDER;
table.AddCell(imgCell1);
DaNet
  • 398
  • 3
  • 6
  • 20

1 Answers1

18

Two things.

First, see this post about wrapping the Image in a Chunk. Basically:

iTextSharp.text.pdf.PdfPCell imgCell1 = new iTextSharp.text.pdf.PdfPCell();
imgCell1.AddElement(new Chunk(img1, 0, 0));

Second, if you want the exact same size then you want to use ScaleAbsolute instead of ScaleToFit. The latter keeps the aspect ratio of the image so a 100x200 image scaled to fit 50x50 would come out as 25x50.

img1.ScaleAbsolute(120f, 155.25f);
Community
  • 1
  • 1
Chris Haas
  • 53,986
  • 12
  • 141
  • 274
  • It look likes the image is the proper size now thanks! Now I have to position it the cell even though it is an element of the cell. In the end I don't think that would be the best alternative for what I am trying to do. – DaNet Nov 23 '11 at 15:56
  • By just using img1.ScaleAbsolute(120f, 155.25f); the images fit the cell perfectly. Cheers Chris! – DaNet Nov 23 '11 at 16:25
  • 2
    If I want my image 35x35 mm then what should I do? How to calculate it in mm? – prem30488 May 12 '14 at 07:45
  • Thankx "ScaleAbsolut" is the solution of my problem. – Durgesh Pandey Jan 28 '16 at 11:19
  • Good mention about wrapping in a Chunk. Been wondering why my scaling wasn't working at all! – Andrew Stephens Aug 10 '17 at 11:25