c# - 如何在 UWP 应用程序中打印?

标签 c# printing uwp windows-10-universal

我正在尝试从我的 UWP 应用打印一些东西。基本上我使用 WebViewBrush 将一些数据绘制到某些 FrameworkElement 的 (Windows.UI.Xaml.Shapes.Rectangle) - 我想在每一页上打印这些矩形之一(一个每页矩形)

我真的希望有人能提供一个非常简单的例子来说明 UWP 中的打印是如何工作的。我自己已经尝试过了,我很乐意提供我的代码,但老实说有数千行 - 所有这些都是我从 Microsoft GitHub 示例中获取并尝试调整的:

老实说,我认为这些例子太复杂了。我想要的只是一种非常简单的打印方式。我也找不到关于这个主题的任何教程,但我想如果有人有一个我可以开始工作的小代码片段,也许我可以在它的基础上进行构建,这样它就可以与矩形一起工作(而不是我现在正在做的 - 采取来自 Microsoft 的一个巨大示例,并试图找出我不需要的部分)。

谢谢。我认为任何能够以简单方式回答这个问题的人都会发现这将成为 future 的明确引用点 - 因为关于这个主题的在线信息非常稀缺。

最佳答案

关于如何在UWP应用程序中打印,您可以按照Print from your app中的步骤进行操作。 .并引用 Printing sample在 GitHub 上。以下是一个简单的示例,演示如何在页面上打印一个矩形。

在 XAML 中,添加一个打印按钮和要打印的矩形。

<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>

在代码隐藏中,处理打印逻辑。

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
}

关于c# - 如何在 UWP 应用程序中打印?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39074684/

相关文章:

java - 从 Java 字典中打印

c# - 是否可以从 ASP.NET 隐藏字段控件恢复扩展属性?

c# - 堆叠条形图

c# - 如何在列表框末尾制作“更多”按钮并处理它?

java 。不缩放打印高分辨率图像

sql - Qt4 : Print a SQL table to PDF

c# - #UWP 改变richeditbox的所有字体颜色

win-universal-app - 部署到商店后 UWP 部署错误 - Windows 10

c# - 在 UWP 后台任务中显示信息

c# - 在网页浏览器控件中打开存储在 byte[] 中的文件