简体   繁体   中英

How to set text alignment in dynamically created FixedDocument

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?

https://docs.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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM