打印标签项

时间:2017-04-03 21:42:34

标签: c# wpf xaml tabcontrol tabitem

如何在XAML / XAML.cs中启用打印整个tabitem或部分tabitem?

我使用下面的代码并能够打印tabitem但我想控制大小和预览。如果我使用横向页面格式,它仍然不会打印整个页面但会截断其中的一部分。

TabItem Header =“Stars

XAML

<Button Margin=" 5,5,5,5" Grid.Row="3" x:Name="PrintOilTab"
        Click="PrintOilTab_Click" Content="Print" FontSize="10"/>

XAML.CS

private void PrintOilTab_Click(object sender, RoutedEventArgs e)
{
    System.Windows.Controls.PrintDialog Printdlg = 
        new System.Windows.Controls.PrintDialog();

    if ((bool)Printdlg.ShowDialog().GetValueOrDefault())
    {
        CompleteOilLimitDiagram.Measure(
            new Size(Printdlg.PrintableAreaWidth,               
                     Printdlg.PrintableAreaHeight));
        Printdlg.PrintVisual(CompleteOilLimitDiagram, "Stars");
    }
}

1 个答案:

答案 0 :(得分:1)

PrintVisual()我从来没有好运过。我必须始终生成FixedDocument,然后使用PrintDocument()

此代码旨在打印ImageSource,但我认为可以通过将控件添加到FixedDocument来轻松调整以打印任何控件:

    using System.Windows.Documents;

    public async void SendToPrinter()
    {
        if (ImageSource == null || Image == null)
            return;

        var printDialog = new PrintDialog();

        bool? result = printDialog.ShowDialog();
        if (!result.Value)
            return;

        FixedDocument doc = GenerateFixedDocument(ImageSource, printDialog);
        printDialog.PrintDocument(doc.DocumentPaginator, "");

    }

    private FixedDocument GenerateFixedDocument(ImageSource imageSource, PrintDialog dialog)
    {
        var fixedPage = new FixedPage();
        var pageContent = new PageContent();
        var document = new FixedDocument();

        bool landscape = imageSource.Width > imageSource.Height;

        if (landscape)
        {
            fixedPage.Height = dialog.PrintableAreaWidth;
            fixedPage.Width = dialog.PrintableAreaHeight;
            dialog.PrintTicket.PageOrientation = PageOrientation.Landscape;
        }
        else
        {
            fixedPage.Height = dialog.PrintableAreaHeight;
            fixedPage.Width = dialog.PrintableAreaWidth;
            dialog.PrintTicket.PageOrientation = PageOrientation.Portrait;
        }

        var imageControl = new System.Windows.Controls.Image {Source = ImageSource,};
        imageControl.Width = fixedPage.Width;
        imageControl.Height = fixedPage.Height;

        pageContent.Width = fixedPage.Width;
        pageContent.Height = fixedPage.Height;

        document.Pages.Add(pageContent);
        pageContent.Child = fixedPage;

        // You'd have to do something different here: possibly just add your 
        // tab to the fixedPage.Children collection instead.
        fixedPage.Children.Add(imageControl);

        return document;
    }