Skriva ut en XPS-fil (WPF .NET)
Ibland vill du lägga till ett nytt utskriftsjobb i utskriftskön utan att öppna en utskriftsdialogruta. Du kan använda någon av de PrintQueue.AddJob metoderna för att göra det. Så här gör du.
I följande exempel använder vi metoden AddJob(String, String, Boolean), en av flera överlagringar av AddJob
, för att:
- Lägg till ett nytt utskriftsjobb för ett XPS-dokument (XML Paper Specification) i standardkön för utskrift.
- Ge det nya jobbet namnet.
- Ange om XPS-dokumentet ska verifieras (med hjälp av parametern
fastCopy
).
När du använder metoden AddJob(String, String, Boolean)
är värdet för parametern fastCopy
en viktig faktor:
- Om du ställer in parametern
fastCopy
påtrue
hoppar XPS-valideringen över och utskriftsjobbet kommer att spolas snabbt utan återkoppling om sidvis-förlopp. - Om du anger parametern
fastCopy
tillfalse
måste tråden som anropar metodenAddJob
ha ett entrådat lägenhetstillstånd, annars utlöses ett undantag. Mer information finns i avsnittet Kommentarer för AddJob(String, String, Boolean).
Lägga till nya utskriftsjobb i kön
Det här exemplet lägger till ett eller flera XPS-dokument i standardkön. Koden kommer att:
- Använd Task.Run för att undvika att blockera användargränssnittstråden eftersom det inte finns någon asynkron version av
AddJob
. - Om parametervärdet
fastCopy
ärfalse
kör du AddJob(String, String, Boolean) på en tråd med entrådat lägenhetstillstånd. - Hämta en referens till standard PrintQueue för LocalPrintServer.
- Anropa
AddJob(String, String, Boolean)
på utskriftsköreferensen, skicka in ett jobbnamn, en XPS-dokumentsökväg och parameternfastCopy
.
Om kön inte pausas och skrivaren fungerar börjar ett utskriftsjobb automatiskt skriva ut när det når toppen av utskriftskön.
Tips
Om du vill undvika dialogrutan Spara utdatafil som när du lägger till ett utskriftsjobb i standardkön kontrollerar du att standardskrivaren inte är Microsoft XPS Document Writer, Microsoft Skriv ut till PDF, eller andra alternativ för att skriva ut till fil.
/// <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;
}
''' <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 Shared Async Function BatchAddToPrintQueueAsync(xpsFilePaths As IEnumerable(Of String), Optional fastCopy As Boolean = False) As Task(Of Boolean)
Dim isAllPrinted As Boolean = True
' Queue some work to run on the ThreadPool.
' Wait for completion without blocking the calling thread.
Await Task.Run(
Sub()
If fastCopy Then
isAllPrinted = BatchAddToPrintQueue(xpsFilePaths, fastCopy)
Else
' Create a thread to call the PrintQueue.AddJob method.
Dim newThread As New Thread(
Sub()
isAllPrinted = BatchAddToPrintQueue(xpsFilePaths, fastCopy)
End Sub
)
' 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()
End If
End Sub
)
Return isAllPrinted
End Function
''' <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 Shared Function BatchAddToPrintQueue(xpsFilePaths As IEnumerable(Of String), fastCopy As Boolean) As Boolean
Dim isAllPrinted As Boolean = 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.
Dim defaultPrintQueue As PrintQueue = LocalPrintServer.GetDefaultPrintQueue()
' Iterate through the document collection.
For Each xpsFilePath As String In xpsFilePaths
' Get document name.
Dim xpsFileName As String = 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.
Dim xpsPrintJob As PrintSystemJobInfo = 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 e As PrintJobException
isAllPrinted = False
Debug.WriteLine($"Failed to add {xpsFileName} to the print queue: {e.Message}\r\n{e.InnerException}")
End Try
Next
Return isAllPrinted
End Function
Tips
Du kan också skriva ut XPS-filer med hjälp av:
- PrintDialog.PrintDocument eller PrintDialog.PrintVisual metoder.
- XpsDocumentWriter.Write och XpsDocumentWriter.WriteAsync-metoder.
Mer information finns i Visa en utskriftsdialogruta och Översikt över utskriftsdokument.
Se även
.NET Desktop feedback