Search code examples
c#wpffixeddocumentfixedpage

Detect if content on FixedPage exceeds bottom boundary


I'm creating a document I'd like to print later. This document shall contain a grid that lists items like a table, including a header row. The number of items varies and therefore it is possible that the grid exceeds the bottom boundary of a single page. When that happens, I'd like to continue on a second page, the "table" header shall be on it again. I 'm adding the rows programatically in a for-loop.

Do you know a way how to detect if the bottom page boundary is exceeded? Maybe there's a different approach.


Solution

  • The Solution is to take a StackPanel as the "root child" for each FixedPage. I then can add content and measure it.

    public StackPanel AddNewPage()
    {
        PageContent pC = new PageContent();
        FixedPage fP = new FixedPage { Width = PageWidth, Height = PageHeight, Margin = Margin };
    
        StackPanel sP = new StackPanel { Width = PageWidth - Margin.Left - Margin.Right };
        fP.Children.Add(sP);
    
        pC.Child = fP;
    
        //FixedDocument
        Document.Pages.Add(pC);
    
        //used later to add content to the page 
        return sP;
    }
    
    public bool IsPageOverfilled(int pageIndex)
    {
        StackPanel sP = (Document.Pages[pageIndex].Child as FixedPage).Children[0] as StackPanel;
        //necessary to recognize new added elements
        sP.UpdateLayout();
        sP.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
    
        if (sP.DesiredSize.Height > MaxPageContentHeight)
            return true;
        else return false;
    }
    

    MaxPageContentHeight is defined as the following:

    double MaxPageContentHeight = PageHeight - Margin.Top - Margin.Bottom;