Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
495 views
in Technique[技术] by (71.8m points)

c# - itextsharp and images sizes

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);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...