mirror of
https://github.com/Stone-Red-Code/docs-desktop.git
synced 2026-09-09 16:06:09 +02:00
Printing in WPF port for .NET (#1156)
* Initial files * update toc * Content update - print-xps-files (user story 1861941) (#1151) * Add C# and VB sample code projects * Fix comments * Update C# and VB code * Add article * Further edits * Reviewer requested edits * Further edits * Use xref to link to API * Minor edits * Content update - invoke-print-dialog (user story 1861941) (#1141) * Content update including C# WPF project * Fix link * Remove test code * Further doc and C# sample edits * Add feature: printing with no print dialog * Separate out specific page range print functionality * Cleanup comments * UI tweaks * Add VB sample code project * Code file formatting * Update dotnet-desktop-guide/net/wpf/documents/how-to-display-print-dialog.md Co-authored-by: Andy (Steve) De George <[email protected]> * Add page range printing * Minor edits * Update dotnet-desktop-guide/net/wpf/documents/snippets/how-to-display-print-dialog/csharp/MainWindow.xaml.cs Co-authored-by: Andy (Steve) De George <[email protected]> * Update dotnet-desktop-guide/net/wpf/documents/how-to-display-print-dialog.md Co-authored-by: Andy (Steve) De George <[email protected]> * Promote example headings * Reorganize and add detail * Minor edits * Add detail * Further edits * Further edits * Add resource links * Add alternative API suggestions to a tip * Minor edit Co-authored-by: Andy (Steve) De George <[email protected]> * Content update - print-overview (user story 1861941) (#1153) * Add C# and VB sample code projects * Add article * Add redirects Co-authored-by: Tris Shores <[email protected]>
This commit is contained in:
co-authored by
Tris Shores
parent
e96218f17e
commit
bdd178c010
@@ -0,0 +1,9 @@
|
||||
<Application x:Class="CodeSampleCsharp.App"
|
||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:local="clr-namespace:CodeSampleCsharp"
|
||||
StartupUri="MainWindow.xaml">
|
||||
<Application.Resources>
|
||||
|
||||
</Application.Resources>
|
||||
</Application>
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Configuration;
|
||||
using System.Data;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using System.Windows;
|
||||
|
||||
namespace CodeSampleCsharp
|
||||
{
|
||||
/// <summary>
|
||||
/// Interaction logic for App.xaml
|
||||
/// </summary>
|
||||
public partial class App : Application
|
||||
{
|
||||
}
|
||||
}
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
using System.Windows;
|
||||
|
||||
[assembly: ThemeInfo(
|
||||
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
|
||||
//(used if a resource is not found in the page,
|
||||
// or application resource dictionaries)
|
||||
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
|
||||
//(used if a resource is not found in the page,
|
||||
// app, or any theme specific resource dictionaries)
|
||||
)]
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>WinExe</OutputType>
|
||||
<TargetFramework>net5.0-windows</TargetFramework>
|
||||
<UseWPF>true</UseWPF>
|
||||
</PropertyGroup>
|
||||
|
||||
</Project>
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
<Window x:Class="CodeSampleCsharp.MainWindow"
|
||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
|
||||
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
|
||||
mc:Ignorable="d"
|
||||
Title="Print an XPS file" Height="149" Width="509">
|
||||
<Grid Margin="0,0,0,10">
|
||||
<Label Content="Enter the path to a folder that contains XPS files" HorizontalAlignment="Left" Margin="27,12,0,0" VerticalAlignment="Top" FontSize="11" Height="25" Width="339"/>
|
||||
<TextBox HorizontalAlignment="Left" Margin="32,35,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="447" FontSize="14" x:Name="txtFolderPath" Height="21"/>
|
||||
<Button Content="Print" HorizontalAlignment="Left" Margin="32,71,0,0" FontSize="14" Width="51" x:Name="btnPrint" Height="28" VerticalAlignment="Top" Click="BtnPrint_Click"/>
|
||||
<CheckBox x:Name="cbxValidateXps" Content="Validate XPS files" HorizontalAlignment="Left" Margin="137,78,0,0" VerticalAlignment="Top" IsChecked="True"/>
|
||||
</Grid>
|
||||
</Window>
|
||||
+137
@@ -0,0 +1,137 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.Printing;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using System.Windows;
|
||||
|
||||
namespace CodeSampleCsharp
|
||||
{
|
||||
/// <summary>
|
||||
/// Interaction logic for MainWindow.xaml.
|
||||
/// </summary>
|
||||
public partial class MainWindow : Window
|
||||
{
|
||||
public MainWindow()
|
||||
{
|
||||
InitializeComponent();
|
||||
}
|
||||
|
||||
private async void BtnPrint_Click(object sender, RoutedEventArgs e)
|
||||
{
|
||||
// Check that the folder exists.
|
||||
if (!Directory.Exists(txtFolderPath.Text))
|
||||
{
|
||||
MessageBox.Show("First select a valid folder path.");
|
||||
return;
|
||||
}
|
||||
|
||||
// Check whether any XPS files exist in the folder.
|
||||
string[] xpsFilePaths = Directory.GetFiles(path: txtFolderPath.Text, searchPattern: "*.xps");
|
||||
if (xpsFilePaths.Length == 0)
|
||||
{
|
||||
MessageBox.Show("No XPS files found.");
|
||||
return;
|
||||
}
|
||||
|
||||
// Determine whether XPS validation is needed.
|
||||
bool fastCopy = cbxValidateXps.IsChecked == false;
|
||||
|
||||
// Batch add a collection of XPS files to the print queue.
|
||||
// Run asynchronously to avoid blocking the UI thread.
|
||||
bool isAllPrinted = await BatchAddToPrintQueueAsync(xpsFilePaths, fastCopy);
|
||||
|
||||
// Show result message.
|
||||
MessageBox.Show($"{(isAllPrinted ? "Added" : "Failed to add")} all documents to the print queue.");
|
||||
}
|
||||
|
||||
// <SampleCode1>
|
||||
/// <summary>
|
||||
/// Asyncronously, add a batch of XPS documents to the print queue using a PrintQueue.AddJob method.
|
||||
/// Handle the thread apartment state required by the PrintQueue.AddJob method.
|
||||
/// </summary>
|
||||
/// <param name="xpsFilePaths">A collection of XPS documents.</param>
|
||||
/// <param name="fastCopy">Whether to validate the XPS documents.</param>
|
||||
/// <returns>Whether all documents were added to the print queue.</returns>
|
||||
public static async Task<bool> BatchAddToPrintQueueAsync(IEnumerable<string> xpsFilePaths, bool fastCopy = false)
|
||||
{
|
||||
bool allAdded = true;
|
||||
|
||||
// Queue some work to run on the ThreadPool.
|
||||
// Wait for completion without blocking the calling thread.
|
||||
await Task.Run(() =>
|
||||
{
|
||||
if (fastCopy)
|
||||
allAdded = BatchAddToPrintQueue(xpsFilePaths, fastCopy);
|
||||
else
|
||||
{
|
||||
// Create a thread to call the PrintQueue.AddJob method.
|
||||
Thread newThread = new(() =>
|
||||
{
|
||||
allAdded = BatchAddToPrintQueue(xpsFilePaths, fastCopy);
|
||||
});
|
||||
|
||||
// Set the thread to single-threaded apartment state.
|
||||
newThread.SetApartmentState(ApartmentState.STA);
|
||||
|
||||
// Start the thread.
|
||||
newThread.Start();
|
||||
|
||||
// Wait for thread completion. Blocks the calling thread,
|
||||
// which is a ThreadPool thread.
|
||||
newThread.Join();
|
||||
}
|
||||
});
|
||||
|
||||
return allAdded;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Add a batch of XPS documents to the print queue using a PrintQueue.AddJob method.
|
||||
/// </summary>
|
||||
/// <param name="xpsFilePaths">A collection of XPS documents.</param>
|
||||
/// <param name="fastCopy">Whether to validate the XPS documents.</param>
|
||||
/// <returns>Whether all documents were added to the print queue.</returns>
|
||||
public static bool BatchAddToPrintQueue(IEnumerable<string> xpsFilePaths, bool fastCopy)
|
||||
{
|
||||
bool allAdded = true;
|
||||
|
||||
// To print without getting the "Save Output File As" dialog, ensure
|
||||
// that your default printer is not the Microsoft XPS Document Writer,
|
||||
// Microsoft Print to PDF, or other print-to-file option.
|
||||
|
||||
// Get a reference to the default print queue.
|
||||
PrintQueue defaultPrintQueue = LocalPrintServer.GetDefaultPrintQueue();
|
||||
|
||||
// Iterate through the document collection.
|
||||
foreach (string xpsFilePath in xpsFilePaths)
|
||||
{
|
||||
// Get document name.
|
||||
string xpsFileName = Path.GetFileName(xpsFilePath);
|
||||
|
||||
try
|
||||
{
|
||||
// The AddJob method adds a new print job for an XPS
|
||||
// document into the print queue, and assigns a job name.
|
||||
// Use fastCopy to skip XPS validation and progress notifications.
|
||||
// If fastCopy is false, the thread that calls PrintQueue.AddJob
|
||||
// must have a single-threaded apartment state.
|
||||
PrintSystemJobInfo xpsPrintJob =
|
||||
defaultPrintQueue.AddJob(jobName: xpsFileName, documentPath: xpsFilePath, fastCopy);
|
||||
|
||||
// If the queue is not paused and the printer is working, then jobs will automatically begin printing.
|
||||
Debug.WriteLine($"Added {xpsFileName} to the print queue.");
|
||||
}
|
||||
catch (PrintJobException e)
|
||||
{
|
||||
allAdded = false;
|
||||
Debug.WriteLine($"Failed to add {xpsFileName} to the print queue: {e.Message}\r\n{e.InnerException}");
|
||||
}
|
||||
}
|
||||
|
||||
return allAdded;
|
||||
}
|
||||
// </SampleCode1>
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user