Notes
L’accès à cette page nécessite une autorisation. Vous pouvez essayer de vous connecter ou de modifier des répertoires.
L’accès à cette page nécessite une autorisation. Vous pouvez essayer de modifier des répertoires.
Parfois, vous souhaiterez ajouter un nouveau travail d’impression à la file d’attente d’impression sans ouvrir de boîte de dialogue d’impression. Vous pouvez utiliser l’une des méthodes PrintQueue.AddJob pour le faire. Voici comment.
Dans l’exemple suivant, nous utilisons la méthode AddJob(String, String, Boolean), l’une des nombreuses surcharges de AddJob
, pour :
- Ajoutez un nouveau travail d’impression pour un document XPS (XML Paper Specification) dans la file d’attente d’impression par défaut.
- Donnez un nom au nouveau poste.
- Spécifiez si le document XPS doit être validé (à l’aide du paramètre
fastCopy
).
Lorsque vous utilisez la méthode AddJob(String, String, Boolean)
, la valeur du paramètre fastCopy
est une considération clé :
- Si vous définissez le paramètre
fastCopy
surtrue
, la validation XPS est ignorée et le travail d’impression est rapidement mis en attente sans commentaires de progression page par page. - Si vous définissez le paramètre
fastCopy
surfalse
, le thread qui appelle la méthodeAddJob
doit avoir un état de thread unique cloisonné, sinon une exception sera levée. Pour plus d’informations, consultez la section Remarques pour AddJob(String, String, Boolean).
Ajouter de nouveaux travaux d’impression à la file d’attente
Cet exemple ajoute un ou plusieurs documents XPS à la file d’attente par défaut. Le code :
- Utilisez Task.Run pour éviter de bloquer le thread d’interface utilisateur, car il n’existe aucune version asynchrone de
AddJob
. - Si la valeur du paramètre
fastCopy
estfalse
, exécutez AddJob(String, String, Boolean) sur un thread avec l’état de thread unique cloisonné. - Obtenez une référence au PrintQueue par défaut du LocalPrintServer.
- Appelez
AddJob(String, String, Boolean)
sur la référence de la file d'attente d'impression, en passant un nom de tâche, un chemin d'accès au document XPS et le paramètrefastCopy
.
Si la file d’attente n’est pas suspendue et que l’imprimante fonctionne, un travail d’impression commence automatiquement à imprimer lorsqu’il atteint le haut de la file d’attente d’impression.
Conseil / Astuce
Pour éviter la boîte de dialogue Enregistrer le fichier de sortie sous lors de l’ajout d’un travail d’impression à la file d’attente par défaut, vérifiez que votre imprimante par défaut n’est pas Microsoft XPS Document Writer, Microsoft Print to PDFou d’autres options d’impression à fichier.
/// <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
Conseil / Astuce
Vous pouvez également imprimer des fichiers XPS à l’aide de :
- méthodes PrintDialog.PrintDocument ou PrintDialog.PrintVisual.
- méthodes XpsDocumentWriter.Write et XpsDocumentWriter.WriteAsync.
Pour plus d’informations, consultez Comment afficher une boîte de dialogue imprimer et Vue d’ensemble de l’impression de documents.
Voir aussi
- PrintQueue.AddJob
- Documents dans WPF
- Comment afficher une boîte de dialogue d'impression
- Vue d’ensemble de l’impression de documents
.NET Desktop feedback