I am creating a two column table in a PDF using iText7, and using CreatePercentArray to set the relative column widths (20%, 80%). In the middle of the table, I have a row containing one cell that spans both columns and contains an image.
When the width of the image is small, the column widths are correct. As the width of the image grows, the column widths progressively change until both are 50%, even though the image width is smaller than the combined width of the columns.
const float SCALE = 1.0f;
float[] colWidths = { 1, 4 };
Table table = new Table(UnitValue.CreatePercentArray(colWidths)).UseAllAvailableWidth();
table.AddCell(new Cell().Add(new Paragraph("row 1, col 1")));
table.AddCell(new Cell().Add(new Paragraph("row 1, col 2")));
Cell image = new Cell(1, 2);
ImageData logoData = ImageDataFactory.Create(@"logo.png");
Image logo= new Image(logoData)
.ScaleAbsolute(170f * SCALE, 50f * SCALE);
image.Add(logo);
table.AddCell(image);
table.AddCell(new Cell().Add(new Paragraph("row 3, col 1")));
table.AddCell(new Cell().Add(new Paragraph("row 3, col 2")));
document.Add(table);
(for the purpose of this test code, the test image has an aspect ratio of 170:50)
If SCALE is set to 1, the column widths are 20:80. If SCALE is increased to 3, the column widths change to 50:50.
At SCALE = 1, the image is wider than column 1, and less wide than both columns combined, but the relative column widths are not affected.
At SCALE = 3, the image is still wider than column 1, and still less wide than both columns combined, but the relative column widths are affected.
I'm at a loss to understand this. I assumed that content which easily fits inside a cell that spans all columns in a table would have no effect on the column widths. But it would appear not. Any advice gratefully received.
In the default mode the widths of the table are calculated by a width distribution algorithm. While details of how it works can be found e.g. in the CSS specification and the iText 7 implementation of the algorithm can be debugged to find out the reason of the observed behavior as iText 7 Core is an open source library, it seems that what you search for is just a way to distribute the table column width in 1:4 ratio.
This is easily achievable with table.SetFixedLayout();
configuration.
Full code:
const float SCALE = 1.0f;
float[] colWidths = { 1, 4 };
Table table = new Table(UnitValue.CreatePercentArray(colWidths)).UseAllAvailableWidth();
table.SetFixedLayout();
table.AddCell(new Cell().Add(new Paragraph("row 1, col 1")));
table.AddCell(new Cell().Add(new Paragraph("row 1, col 2")));
Cell image = new Cell(1, 2);
ImageData logoData = ImageDataFactory.Create(@"logo.png");
Image logo= new Image(logoData)
.ScaleAbsolute(170f * SCALE, 50f * SCALE);
image.Add(logo);
table.AddCell(image);
table.AddCell(new Cell().Add(new Paragraph("row 3, col 1")));
table.AddCell(new Cell().Add(new Paragraph("row 3, col 2")));
document.Add(table);
Visual result: