如何在UWP应用中打印? [英] How to print in UWP app?

查看:39
本文介绍了如何在UWP应用中打印?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从我的UWP应用中打印出一些内容.基本上,我已经使用WebViewBrush在一些 FrameworkElement 的(Windows.UI.Xaml.Shapes.Rectangle)上绘制一些数据,并且我想在每页上打印这些矩形之一(一个每页矩形)

I am trying to print out something from my UWP app. Basically I've used a WebViewBrush to draw some data on to some FrameworkElement's (Windows.UI.Xaml.Shapes.Rectangle) - and I want to print one of these Rectangles on each page (one rectangle per page)

我真的希望有人能够提供一个非常简单的示例,说明UWP中的打印工作原理.我已经尝试过了,很高兴提供自己的代码,但是说实话,有数千行-所有这些都是我从Microsoft GitHub示例中提取的,并尝试了以下调整:

I was really hoping someone could provide a very simple example of how printing in UWP works. I have tried it myself and I am happy to provide my code, but there are honestly thousands of lines - all of which I've taken from the Microsoft GitHub examples and tried tweaking:

老实说,我认为这些例子太复杂了.我想要的只是一种非常简单的打印方式.我也找不到与此主题有关的任何教程,但是我想知道是否有人可以使用我的小代码片段,也许我可以在其上进行构建,以便它可以与Rectangles一起使用(而不是我现在正在做的事情-取得微软的一个巨大例子,试图找出我不需要的部分.

Honestly, those examples are too complicated I think. What I want is just a really simple way to print. I can't find any tutorials on this topic either, but I figure if someone has a small code snippet that I could get working maybe I could build on it so it will work with Rectangles (rather than what I'm doing now - taking a huge example from Microsoft and trying to figure out which parts I don't need).

谢谢.我认为任何可以通过简单方式回答此问题的人都会发现,这将成为将来的明确参考点-因为有关该主题的在线信息非常稀缺.

Thank you. I think anyone that can answer this question in a simple way will find this will become a definitive reference point in the future - because information online about this topic is so scarce.

推荐答案

有关如何在UWP应用程序中进行打印,您可以按照 打印示例 在GitHub上.以下是一个简单的示例,演示了如何在页面上打印矩形.

For how to print in UWP apps, you can follow the steps in Print from your app. And also refer to the Printing sample on GitHub. Following is a simple sample demonstrates how to print a rectangle on the page.

在XAML中,添加打印按钮和要打印的矩形.

In XAML, add a print button and the rectangle to be printed.

<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto" />
        <RowDefinition />
    </Grid.RowDefinitions>
    <Button HorizontalAlignment="Center" Click="PrintButtonClick">Print</Button>
    <Rectangle x:Name="RectangleToPrint"
               Grid.Row="1"
               Width="500"
               Height="500">
        <Rectangle.Fill>
            <ImageBrush ImageSource="Assets/img.jpg" />
        </Rectangle.Fill>
    </Rectangle>
</Grid>

然后在代码背后,处理打印逻辑.

And in code-behind, handle the print logic.

public sealed partial class MainPage : Page
{
    private PrintManager printMan;
    private PrintDocument printDoc;
    private IPrintDocumentSource printDocSource;

    public MainPage()
    {
        this.InitializeComponent();
    }

    #region Register for printing

    protected override void OnNavigatedTo(NavigationEventArgs e)
    {
        // Register for PrintTaskRequested event
        printMan = PrintManager.GetForCurrentView();
        printMan.PrintTaskRequested += PrintTaskRequested;

        // Build a PrintDocument and register for callbacks
        printDoc = new PrintDocument();
        printDocSource = printDoc.DocumentSource;
        printDoc.Paginate += Paginate;
        printDoc.GetPreviewPage += GetPreviewPage;
        printDoc.AddPages += AddPages;
    }

    #endregion

    #region Showing the print dialog

    private async void PrintButtonClick(object sender, RoutedEventArgs e)
    {
        if (PrintManager.IsSupported())
        {
            try
            {
                // Show print UI
                await PrintManager.ShowPrintUIAsync();
            }
            catch
            {
                // Printing cannot proceed at this time
                ContentDialog noPrintingDialog = new ContentDialog()
                {
                    Title = "Printing error",
                    Content = "\nSorry, printing can' t proceed at this time.",
                    PrimaryButtonText = "OK"
                };
                await noPrintingDialog.ShowAsync();
            }
        }
        else
        {
            // Printing is not supported on this device
            ContentDialog noPrintingDialog = new ContentDialog()
            {
                Title = "Printing not supported",
                Content = "\nSorry, printing is not supported on this device.",
                PrimaryButtonText = "OK"
            };
            await noPrintingDialog.ShowAsync();
        }
    }

    private void PrintTaskRequested(PrintManager sender, PrintTaskRequestedEventArgs args)
    {
        // Create the PrintTask.
        // Defines the title and delegate for PrintTaskSourceRequested
        var printTask = args.Request.CreatePrintTask("Print", PrintTaskSourceRequrested);

        // Handle PrintTask.Completed to catch failed print jobs
        printTask.Completed += PrintTaskCompleted;
    }

    private void PrintTaskSourceRequrested(PrintTaskSourceRequestedArgs args)
    {
        // Set the document source.
        args.SetSource(printDocSource);
    }

    #endregion

    #region Print preview

    private void Paginate(object sender, PaginateEventArgs e)
    {
        // As I only want to print one Rectangle, so I set the count to 1
        printDoc.SetPreviewPageCount(1, PreviewPageCountType.Final);
    }

    private void GetPreviewPage(object sender, GetPreviewPageEventArgs e)
    {
        // Provide a UIElement as the print preview.
        printDoc.SetPreviewPage(e.PageNumber, this.RectangleToPrint);
    }

    #endregion

    #region Add pages to send to the printer

    private void AddPages(object sender, AddPagesEventArgs e)
    {
        printDoc.AddPage(this.RectangleToPrint);

        // Indicate that all of the print pages have been provided
        printDoc.AddPagesComplete();
    }

    #endregion

    #region Print task completed

    private async void PrintTaskCompleted(PrintTask sender, PrintTaskCompletedEventArgs args)
    {
        // Notify the user when the print operation fails.
        if (args.Completion == PrintTaskCompletion.Failed)
        {
            await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () =>
            {
                ContentDialog noPrintingDialog = new ContentDialog()
                {
                    Title = "Printing error",
                    Content = "\nSorry, failed to print.",
                    PrimaryButtonText = "OK"
                };
                await noPrintingDialog.ShowAsync();
            });
        }
    }

    #endregion
}

这篇关于如何在UWP应用中打印?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆