How to set text alignment in dynamically created FixedDocument

372 Views Asked by At

I am creating a report through FixedDocument and I am doing it in the code behind to dynamically add data to the report.

I started using FixedDocument today and got stuck in aligning texts. It does not seem to center align. Here's my code:

using System.Windows.Documents;
....
public void GenerateReport()
{
    FixedDocument document = new FixedDocument();
    PageContent content = new PageContent();

    FixedPage page = new FixedPage();
    page.Width = document.DocumentPaginator.PageSize.Width;
    page.Height = document.DocumentPaginator.PageSize.Height;
    page.Background = System.Windows.Media.Brushes.AliceBlue;

    //header first line
    System.Windows.Controls.Canvas canvas = new System.Windows.Controls.Canvas();
    canvas.Width = document.DocumentPaginator.PageSize.Width;

    FixedPage.SetTop(canvas, 15);
    FixedPage.SetLeft(canvas, 15);

    System.Windows.Controls.TextBlock block = new System.Windows.Controls.TextBlock();
    block.FontSize = 11;
    block.FontWeight = FontWeights.Bold;
    block.FontFamily = new System.Windows.Media.FontFamily("Tahoma");
    block.Text = "This is the first line";
    block.HorizontalAlignment = HorizontalAlignment.Center;
               
    canvas.Children.Add(block);

    page.Children.Add(canvas);

    //header second line
    System.Windows.Controls.TextBlock block2 = new System.Windows.Controls.TextBlock(); block.FontSize = 11;
    block2.FontWeight = FontWeights.Bold;
    block2.FontFamily = new System.Windows.Media.FontFamily("Tahoma");
    block2.Text = "Daily Report";

    var canvas2 = new System.Windows.Controls.Canvas();
    canvas2.Children.Add(block2);

    FixedPage.SetTop(canvas2, 30);
    FixedPage.SetTop(canvas2, 30);
    FixedPage.SetLeft(canvas2, 15);
    FixedPage.SetRight(canvas2, 15);

    canvas2.Width = document.DocumentPaginator.PageSize.Width;
                
    page.Children.Add(canvas2);

    ((IAddChild)content).AddChild(page);
    document.Pages.Add(content);
}

How will I do the alignment right?

1

There are 1 best solutions below

1
Cheez Hearts On

https://learn.microsoft.com/en-us/dotnet/api/system.windows.documents.flowdocument?view=net-5.0#properties I'm not sure if you can do this with FixedDocument. This is available in Flowdocument though with the TextAlignmentProperty.