Setting Column Widths to Dynamically resize depending on length of content

I am creating a table and would like for the columns to resize themselves dynamically (much as they do in HTML) depending on the size of the longest bit of content within the cell. I’ve tried:

myTable.ColumnAdjustment = ColumnAdjustmentType.AutoFitToWindow

but this gives each column the same width regardless of the content.

Any ideas?

Thanks!

Laurie

Hi Laurie,


Thanks for your inquiry. Please check following documentation link for setting column width dynamically in a table row. Hopefully it will serve the purpose.


Please feel free to contact us for any further assistance.

Best Regards,

Near as I can tell, that code sets the width to the calculated width of the entire table divided by the total number of columns in a row, which will be the same width for each row. I’m looking for something that will resize depending on the length of the content.


Hi Laurie,


Thanks for sharing more details. Please check following code snippet to set column width according to column contents. Hopefully it will help you to accomplish your requirements.

Aspose.Pdf.Generator.Pdf pdf = new Aspose.Pdf.Generator.Pdf();
Aspose.Pdf.Generator.Section sec = pdf.Sections.Add();
//Create a table object and add it to the paragraphs collection of the section
Aspose.Pdf.Generator.Table tab1 = new Aspose.Pdf.Generator.Table();
sec.Paragraphs.Add(tab1);
//Set the column widths and default cell border of the table
tab1.ColumnWidths = “50 50 50”;
tab1.DefaultCellBorder = new Aspose.Pdf.Generator.BorderInfo((int)Aspose.Pdf.Generator.BorderSide.All, 1F);
//Prepare an array of string values to be added to table
string[] data = new string[] { “Sample Text”, “8.4”, “Its test to set column width as per contnents” };
//Import the contents of the array created in above step
tab1.ImportArray(data, 0, 0, true);

// define the variable to keep record of number of columns in table
int TableColumn = 0;
foreach (Aspose.Pdf.Generator.Cell InnerCell in tab1.Rows[0].Cells)
{
//Call GetMaxColumnWidth and pass the column number whose minimum width is needed
float width = tab1.GetMaxColumnWidth(pdf, TableColumn);
//Call SetColumnWidth and pass the column number with minimum width
tab1.SetColumnWidth(TableColumn, width);
// increase the value of variable holding the column count information
TableColumn += 1;
}
//save the resultant PDF
pdf.Save(myDir+“DynamicColumnWidth_out.pdf”);

Please feel free to contact us for any further assistance.

Best Regards,