The PDF is composed by serveral paragraphs added to the document, and there is a long table which need to set started from top of one page(not the first page) which means a paragraph will be splitted to two parts.
If the table is short(length not exceed the page height), it can be done gracefully by handling Page Event of start page, just added the table to the canvas with the fixed position and size, and set the document's top margin.
PdfDocumentEvent docEvent = (PdfDocumentEvent)currentEvent;
PdfDocument pdfDoc = docEvent.GetDocument();
PdfPage page = docEvent.GetPage();
var currentPageNumber = pdfDoc.GetPageNumber(page);
var addingTablesOfPage = addingTables.Where(t => t.PageNumber == currentPageNumber && t.Prepared).ToList();
if (addingTablesOfPage != null && addingTablesOfPage.Count > 0)
{
PdfCanvas canvas = new PdfCanvas(page.NewContentStreamBefore(), page.GetResources(), pdfDoc);
PageSize pageSize = pdfDoc.GetDefaultPageSize();
var pageHeight = pageSize.GetHeight() - Constants.DocumentMargins[0] - Constants.DocumentMargins[2];
var pageWidth = pageSize.GetWidth() - Constants.DocumentMargins[1] - Constants.DocumentMargins[3];
var totalHeight = 0f;
var alignRight = false;
// add tables to the top of page
foreach (var table in addingTablesOfPage.OrderBy(t => t.Type).ToList())
{
var tableWidth = 0f;
float coordX = 0;
tableWidth = pageWidth;
coordX = pageSize.GetX() + doc.GetLeftMargin();
totalHeight += table.TableHeight;
float coordY = pageSize.GetTop() - Constants.DocumentMargins[0] - totalHeight;
Rectangle rect = new Rectangle(coordX, coordY, tableWidth, table.TableHeight);
var tableCanvas = new Canvas(canvas, rect);
tableCanvas.Add(table.Table);
tableCanvas.Close();
}
float topMargin = Constants.DocumentMargins[0] + totalHeight;
doc.SetTopMargin(topMargin);
}
else
{
doc.SetTopMargin(Constants.DocumentMargins[0]);
}
But here the table is too long which will be splitted to multi pages. As far as I known, Canvas class is primarily aimed at cases when you need to add elements to a specific predefined area on a page / XObject and it is not aimed at overflowing your content to next areas. So how can I achieve the behavior?
Thank you!