When we create nested grid inside a cell, that cell does not autoexpand.
Why there is no "Autogrow" or similar property on a cell?
How can we force cell to accomodate for the inner grid content?
public void NestedGridClips()
{
using (PdfDocument pdfDocument = new PdfDocument())
{
//Create the page
var section = pdfDocument.Sections.Add();
var pdfPage = section.Pages.Add();
PdfGrid parentGrid = new PdfGrid();
FillGrid(parentGrid, "parentGrid", 3, 3, 40);
PdfGrid pGrid = new PdfGrid();
parentGrid.Rows[0].Cells[0].Value = pGrid; // Set nested grid to the first cell
FillGrid(pGrid, "pGrid", 5, 4, rowHeight: 20);
parentGrid.Draw(pdfPage, PointF.Empty, new PdfGridLayoutFormat {Break = PdfLayoutBreakType.FitPage, Layout = PdfLayoutType.Paginate});
void FillGrid(PdfGrid grid, string name, int iMax, int jMax, int? rowHeight = null)
{
for (int j = 0; j < jMax; j++)
{
grid.Columns.Add();
grid.Columns[j].Width = 50 + 5 * j;
}
for (int i = 0; i < iMax; i++)
{
var row = grid.Rows.Add();
if (rowHeight.HasValue)
{
row.Height = rowHeight.Value;
}
for (int j = 0; j < jMax; j++)
{
var cell = grid.Rows[i].Cells[j];
cell.Value = $"grid: {name}. i:{i},j:{j}";
}
}
}
//Save the document
pdfDocument.Save("NestedTable.pdf");
//Close the document
pdfDocument.Close(true);
//This will open the PDF file so, the result will be seen in default PDF viewer
System.Diagnostics.Process.Start("NestedTable.pdf");
}
}
|
static void FillGrid(PdfGrid grid, string name, int iMax, int jMax, int? rowHeight = null)
{
for (int j = 0; j < jMax; j++)
{
grid.Columns.Add();
//grid.Columns[j].Width = 50 + 5 * j;
}
for (int i = 0; i < iMax; i++)
{
var row = grid.Rows.Add();
for (int j = 0; j < jMax; j++)
{
var cell = grid.Rows[i].Cells[j];
cell.Value = $"grid: {name}. i:{i},j:{j}";
}
}
} |
Our code base is rather generic and always sets minimal row height and columns' width before outputting contents to cells.
We need a way for cells to grow to fit content unknown a priori.
We tried calculating grid height after it's laid out (CurrentHeight is a property of an object wrapping PdfGrid):
public float CurrentHeight
{
get
{
//Create a new document.
using (PdfDocument doc = new PdfDocument())
{
//Add a page
PdfPage page = doc.Pages.Add();
//Create Pdf graphics for the page
PdfGraphics graphics = page.Graphics;
//Draw the table
PdfLayoutResult result = this.grid.Draw(page, new PointF(0, 0));
float height = result.Bounds.Height;
//Close the document
doc.Close();
return height;
}
}
}
and update row.Height to it on a hosting PdfGridRow
var height = grid.CurrentHeight;
if (row.Height < height)
{
row.Height = height;
}
but somehow it breaks other parts of a document.
We set width and height because we are reading these values from a template. Some layout has empty rows with a fixed height to create empty space in an output. If we skip setting row height, they will not render at all, since it has no content from Syncfusion point of view.