UWP Печать длинных таблиц данных, которые необходимо распространить на несколько страниц - PullRequest
0 голосов
/ 25 мая 2019

Я делаю бухгалтерскую программу с использованием (uwp, c #, MySQL), я хочу знать при печати отчетов, если сетка данных длинна, как расширить остальные до новых страниц, чтобы весь отчет печатался на нескольких страницах.

я использовал файл printhelp.cs, который находится в образце печати: https://github.com/Microsoft/Windows-universal-samples/tree/master/Samples/Printing, но он печатал сетку данных только на одной странице и не расширял остальные на другие страницы.

UWP XAML:

<Grid>
    <controls:DataGrid Grid.Row="2" Grid.RowSpan="5" Grid.ColumnSpan="2"
        x:Name="TextContent"
        Foreground="Black"
        Background="White"
        ItemsSource="{x:Bind SelectSOA()}"
        AutoGenerateColumns="False"    
        GridLinesVisibility="Horizontal">



        <controls:DataGrid.Columns>
            <controls:DataGridTextColumn   Header="ID" Binding="{Binding ID}" />
            <controls:DataGridTextColumn Header="Account" Binding="{Binding Principal}" />
            <controls:DataGridTextColumn Header="Balance" Binding="{Binding Client}" />
        </controls:DataGrid.Columns>

    <RichTextBlockOverflow  x:Name="FirstLinkedContainer" OverflowContentTarget="{Binding ElementName=ContinuationPageLinkedContainer}" Grid.Row="2" Grid.Column="0"/>
    <RichTextBlockOverflow x:Name="ContinuationPageLinkedContainer" Grid.Row="3" Grid.ColumnSpan="2"/>


</Grid>

Я ожидаю при печати, если сетка данных будет продолжаться до следующей страницы.но он печатает только первую страницу и не распространяет остальные на новые страницы.

1 Ответ

0 голосов
/ 27 мая 2019

Вы можете использовать класс Print Helper для печати DataGrid, но вам все равно придется вручную разбивать свои данные на страницы с выделенным кодом.

Чтобы узнать, как использовать этот класс для печати элемента управления XAML, ознакомьтесь с инструментарием Windows Community Toolkit PrintHelper .

Согласно этому примеру, я делаю небольшие изменения, чтобы сделать простой пример кода для вашей справки:

<Grid>
    <Grid x:Name="RootGrid"
          HorizontalAlignment="Center"
          VerticalAlignment="Center">
        <Grid.RowDefinitions>
            <RowDefinition Height="*" />
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
        </Grid.RowDefinitions>
        <Grid x:Name="Container"
              Grid.RowSpan="2"
              Opacity="0" />
        <Grid x:Name="CustomPrintContainer"
              Opacity="0" />
        <Grid x:Name="DirectPrintContainer">
            <Grid x:Name="PrintableContent">
                <Grid x:Name="XamlRoot" />
            </Grid>
        </Grid>
    </Grid>
    <Button Content="Print" Click="Button_Click" VerticalAlignment="Bottom"></Button>
</Grid>
public List<Person> Persons { get; set; }

    public MainPage()
    {
        this.InitializeComponent();

        Persons = new List<Person>();
        for (int i = 0; i < 100; i++)
        {
            Persons.Add(new Person
            {
                PersonId = i,
                FirstName = "FirstName" + i,
                LastName = "LastName" + i,
                Position = "Network Administrator " + i
            });
        }
    }

    private PrintHelper _printHelper;

    private async void Button_Click(object sender, RoutedEventArgs e)
    {
        _printHelper = new PrintHelper(CustomPrintContainer);

        var pageNumber = 0;

        for (int i = 0; i < Persons.Count; i = i + 10)
        {
            var grid = new Grid();
            grid.RowDefinitions.Add(new RowDefinition() { Height = GridLength.Auto });
            grid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(1, GridUnitType.Star) });
            grid.RowDefinitions.Add(new RowDefinition() { Height = GridLength.Auto });

            // Static header
            var header = new TextBlock { Text = "Custom Print", Margin = new Thickness(0, 0, 0, 20) };
            Grid.SetRow(header, 0);
            grid.Children.Add(header);

            // Main content with layout from data template
            var dataGrid = new DataGrid();
            dataGrid.AutoGenerateColumns = true;
            dataGrid.ItemsSource = Persons.Skip(i).Take(10);
            Grid.SetRow(dataGrid, 1);
            grid.Children.Add(dataGrid);

            // Footer with page number
            pageNumber++;
            var footer = new TextBlock { Text = string.Format("page {0}", pageNumber), Margin = new Thickness(0, 20, 0, 0) };
            Grid.SetRow(footer, 2);
            grid.Children.Add(footer);

            _printHelper.AddFrameworkElementToPrint(grid);
        }

        _printHelper.OnPrintCanceled += _printHelper_OnPrintCanceled;
        _printHelper.OnPrintFailed += _printHelper_OnPrintFailed;
        _printHelper.OnPrintSucceeded += _printHelper_OnPrintSucceeded;

        var printHelperOptions = new PrintHelperOptions(false);
        printHelperOptions.Orientation = Windows.Graphics.Printing.PrintOrientation.Default;
        printHelperOptions.AddDisplayOption(StandardPrintTaskOptions.Orientation);
        await _printHelper.ShowPrintUIAsync("print sample", printHelperOptions);
    }
public class Person
{
    public int PersonId { get; set; }
    public int DepartmentId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Position { get; set; }
}

enter image description here

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...