How to print in UWP app?

I am trying to print something from my UWP application. I basically used WebViewBrush to draw some data on some FrameworkElement (Windows.UI.Xaml.Shapes.Rectangle) - and I want to print one of these rectangles on each page (one rectangle per page)

I really hoped that someone could provide a very simple example of how printing works in UWP. I tried this myself, and I'm happy to provide my code, but there are honestly thousands of lines - all of which I took from Microsoft GitHub examples and tried to tweak:

Honestly, these examples are too complex, I think. I want just a very simple way to print. I also can’t find any tutorials on this topic, but I suggest that if someone has a small piece of code that I could get, maybe I could build it, so it will work with Rectangles (and not the one what I'm doing now) is a huge example from Microsoft and an attempt to find out which parts I do not need).

Thanks. I think that anyone who can answer this question in a simple way will find that this will become the final reference point in the future, because the information on the Internet on this topic is so scarce.

+11
source share
3 answers

In order to print in UWP applications, you can follow the steps in Print from your application . Also, see Printing Example on GitHub. The following is a simple example demonstrating how to print a rectangle on a page.

In XAML, add a print button and a rectangle to print.

 <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 reverse the print logic. A.

 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 } 
+19
source

I am also struggling with this. I switched to an example SDK. This solution may be useful to you. If there is a way that you can put what you want to print in a RichTextBox, you can create paragraphs for it programmatically. And replace the RichTextBox in the SDK example with an empty StackPanel to which you specified the grid requirements, and this will solve your problem. My problem was not exactly the same problem, because I did this with the creation of 2 column lists of products. The trick was using a CourierNew fixed-width font in my example.

On your page that invokes print libraries, you must have this in XAML

<Canvas x:Name="PrintCanvas" Opacity="0"/>

On the page replacing the PageToPrint page, you can build this material directly in the designer. I pass the collection to a page instance and then compute the layout directly in the PageToPrint lookup, like this ,,

  private void MakeThePrintOut() { RichTextBlock gutOne = initBlock(); PopulateBlock(gutOne); ContentStack.Children.Add(gutOne); } private RichTextBlock initBlock() { RichTextBlock gutInitBlock = new RichTextBlock(); gutInitBlock.Foreground = new SolidColorBrush(Windows.UI.Colors.Black); gutInitBlock.FontSize = 18; gutInitBlock.OverflowContentTarget = FirstLinkedContainer; gutInitBlock.FontFamily = new FontFamily("Courier New"); gutInitBlock.VerticalAlignment = VerticalAlignment.Top; gutInitBlock.HorizontalAlignment = HorizontalAlignment.Left; return gutInitBlock; } private void PopulateBlock( RichTextBlock Blocker) { bool firstItem = true; int firstLength = 0; Paragraph paraItem = null; Run itemRun = null; string CurrentIsle = "None"; foreach( Grocery j in Grocs) { if (j.Isle != CurrentIsle) { if ((CurrentIsle != "None") && (!firstItem)) { paraItem.Inlines.Add(itemRun); Blocker.Blocks.Add(paraItem); } CurrentIsle = j.Isle; firstItem = true; Paragraph paraIsle = new Paragraph(); Run paraRan = new Run(); paraRan.Text = " " + j.Isle; paraIsle.Inlines.Add(paraRan); Blocker.Blocks.Add(paraIsle); } if (firstItem) { paraItem = new Paragraph(); itemRun = new Run(); itemRun.Text = " [] " + j.Item; firstLength = j.Item.Length; firstItem = false; } else { firstItem = true; string s = new string(' ', 30 - firstLength); itemRun.Text += s + "[] " + j.Item; paraItem.Inlines.Add(itemRun); Blocker.Blocks.Add(paraItem); } } if (!firstItem) { paraItem.Inlines.Add(itemRun); Blocker.Blocks.Add(paraItem); } } 

This is not exactly what you are looking for, but I know how difficult it is to find something that makes sense to answer the question about printing. If you want to see the full example, my GitHub.com/Gibbloggen GutenbergOne project was my prototype that I developed for this. And I also imported EssentialGrocer into my main project, this is also open source in the same place. This, only today, includes printing a shopping list.

Hope some of this helps, I really struggled with this.

+1
source

Interesting! What about the code in VB?

0
source

All Articles