Les impressions PDF à orientations mixtes impriment chaque page au format paysage

This article was translated from English: Does it need improvement?
Translated
View the article in English

IronPrint 2026.1.5 ne préserve pas l'orientation par page lors de l'impression d'un PDF qui mélange des pages en portrait et en paysage. Chaque page atteint l'imprimante au format paysage, quelle que soit son orientation originale.

Cela affecte 2026.1.5 sur Windows 10 et Windows Server 2022 sous .NET 8. Aucun correctif n'existe pour cette version.

Le moteur applique une seule orientation à l'ensemble du document au lieu de lire les dimensions de chaque page. Diviser le fichier en lots de pages de même orientation et imprimer chaque lot séparément rétablit la sortie correcte.

Solution

Recommandé : imprimez le PDF par lots cohérents en termes d'orientation au lieu de le faire en une seule opération.

1. Détecter l'orientation de chaque page

Ouvrez le PDF et comparez la largeur de chaque page à sa hauteur. Une page plus large que haute est au format paysage ; tout le reste est au format portrait.

2. Regroupez les pages ayant la même orientation consécutive

Parcourez les pages dans l'ordre et commencez un nouveau lot chaque fois que l'orientation change. Chaque lot finit par être une plage de pages contiguës avec une orientation.

3. Imprimez chaque lot comme une opération distincte

Envoyer chaque plage séparément permet à l'imprimante d'appliquer l'orientation de cette plage, plutôt que de forcer l'ensemble du document au format paysage.

4. Gérez les copies multiples manuellement

Étant donné que le document est maintenant divisé en plusieurs travaux, bouclez une fois par copie et imprimez la séquence complète des lots chaque fois. Cela préserve l'ordre des pages pour chaque copie.

Implémentation complète :

using IronPrint;
using IronPdf;
await PrintDocumentByOrientationBatchesAsync(
    documentPath: documentPath,
    printerName: printerName,
    numberOfCopies: effectiveCopies);
async Task PrintDocumentByOrientationBatchesAsync(
    string documentPath,
    string printerName,
    int numberOfCopies)
{
    var tempFolder = Path.Combine(
        Path.GetTempPath(),
        "ironprint-orientation-workaround",
        Guid.NewGuid().ToString("N"));
    Directory.CreateDirectory(tempFolder);
    try
    {
        using var pdf = PdfDocument.FromFile(documentPath);
        var batches = GetConsecutiveOrientationBatches(pdf);
        // Since the document is printed in multiple jobs, copies are handled manually
        // to preserve the full document order per copy.
        for (var copy = 1; copy <= numberOfCopies; copy++)
        {
            foreach (var batch in batches)
            {
                var batchPath = Path.Combine(
                    tempFolder,
                    $"copy_{copy}_pages_{batch.StartPageNumber}_{batch.EndPageNumber}_{batch.Orientation}.pdf");
                using var batchPdf = pdf.CopyPages(batch.StartIndex, batch.EndIndex);
                batchPdf.SaveAs(batchPath);
                var printSettings = new PrintSettings
                {
                    PrinterName = printerName,
                    NumberOfCopies = 1,
                    PaperOrientation = batch.Orientation == DetectedPageOrientation.Landscape
                        ? PaperOrientation.Landscape
                        : PaperOrientation.Portrait,
                    PaperSize = PaperSize.PrinterDefault
                };
                await Printer.PrintAsync(batchPath, printSettings);
                // Optional delay to help ensure print jobs are queued in order.
                await Task.Delay(500);
            }
        }
    }
    finally
    {
        try
        {
            Directory.Delete(tempFolder, recursive: true);
        }
        catch
        {
            // Ignore cleanup errors in case the print spooler is still accessing the files.
        }
    }
}
List<PageOrientationBatch> GetConsecutiveOrientationBatches(PdfDocument pdf)
{
    var batches = new List<PageOrientationBatch>();
    if (pdf.PageCount == 0)
    {
        return batches;
    }
    var currentOrientation = GetPageOrientation(pdf.Pages[0].Width, pdf.Pages[0].Height);
    var batchStartIndex = 0;
    for (var pageIndex = 1; pageIndex < pdf.PageCount; pageIndex++)
    {
        var page = pdf.Pages[pageIndex];
        var pageOrientation = GetPageOrientation(page.Width, page.Height);
        if (pageOrientation != currentOrientation)
        {
            batches.Add(new PageOrientationBatch(
                StartIndex: batchStartIndex,
                EndIndex: pageIndex - 1,
                Orientation: currentOrientation));
            batchStartIndex = pageIndex;
            currentOrientation = pageOrientation;
        }
    }
    batches.Add(new PageOrientationBatch(
        StartIndex: batchStartIndex,
        EndIndex: pdf.PageCount - 1,
        Orientation: currentOrientation));
    return batches;
}
DetectedPageOrientation GetPageOrientation(double width, double height)
{
    return width > height
        ? DetectedPageOrientation.Landscape
        : DetectedPageOrientation.Portrait;
}
record PageOrientationBatch(
    int StartIndex,
    int EndIndex,
    DetectedPageOrientation Orientation)
{
    public int StartPageNumber => StartIndex + 1;
    public int EndPageNumber => EndIndex + 1;
}
enum DetectedPageOrientation
{
    Portrait,
    Landscape
}
using IronPrint;
using IronPdf;
await PrintDocumentByOrientationBatchesAsync(
    documentPath: documentPath,
    printerName: printerName,
    numberOfCopies: effectiveCopies);
async Task PrintDocumentByOrientationBatchesAsync(
    string documentPath,
    string printerName,
    int numberOfCopies)
{
    var tempFolder = Path.Combine(
        Path.GetTempPath(),
        "ironprint-orientation-workaround",
        Guid.NewGuid().ToString("N"));
    Directory.CreateDirectory(tempFolder);
    try
    {
        using var pdf = PdfDocument.FromFile(documentPath);
        var batches = GetConsecutiveOrientationBatches(pdf);
        // Since the document is printed in multiple jobs, copies are handled manually
        // to preserve the full document order per copy.
        for (var copy = 1; copy <= numberOfCopies; copy++)
        {
            foreach (var batch in batches)
            {
                var batchPath = Path.Combine(
                    tempFolder,
                    $"copy_{copy}_pages_{batch.StartPageNumber}_{batch.EndPageNumber}_{batch.Orientation}.pdf");
                using var batchPdf = pdf.CopyPages(batch.StartIndex, batch.EndIndex);
                batchPdf.SaveAs(batchPath);
                var printSettings = new PrintSettings
                {
                    PrinterName = printerName,
                    NumberOfCopies = 1,
                    PaperOrientation = batch.Orientation == DetectedPageOrientation.Landscape
                        ? PaperOrientation.Landscape
                        : PaperOrientation.Portrait,
                    PaperSize = PaperSize.PrinterDefault
                };
                await Printer.PrintAsync(batchPath, printSettings);
                // Optional delay to help ensure print jobs are queued in order.
                await Task.Delay(500);
            }
        }
    }
    finally
    {
        try
        {
            Directory.Delete(tempFolder, recursive: true);
        }
        catch
        {
            // Ignore cleanup errors in case the print spooler is still accessing the files.
        }
    }
}
List<PageOrientationBatch> GetConsecutiveOrientationBatches(PdfDocument pdf)
{
    var batches = new List<PageOrientationBatch>();
    if (pdf.PageCount == 0)
    {
        return batches;
    }
    var currentOrientation = GetPageOrientation(pdf.Pages[0].Width, pdf.Pages[0].Height);
    var batchStartIndex = 0;
    for (var pageIndex = 1; pageIndex < pdf.PageCount; pageIndex++)
    {
        var page = pdf.Pages[pageIndex];
        var pageOrientation = GetPageOrientation(page.Width, page.Height);
        if (pageOrientation != currentOrientation)
        {
            batches.Add(new PageOrientationBatch(
                StartIndex: batchStartIndex,
                EndIndex: pageIndex - 1,
                Orientation: currentOrientation));
            batchStartIndex = pageIndex;
            currentOrientation = pageOrientation;
        }
    }
    batches.Add(new PageOrientationBatch(
        StartIndex: batchStartIndex,
        EndIndex: pdf.PageCount - 1,
        Orientation: currentOrientation));
    return batches;
}
DetectedPageOrientation GetPageOrientation(double width, double height)
{
    return width > height
        ? DetectedPageOrientation.Landscape
        : DetectedPageOrientation.Portrait;
}
record PageOrientationBatch(
    int StartIndex,
    int EndIndex,
    DetectedPageOrientation Orientation)
{
    public int StartPageNumber => StartIndex + 1;
    public int EndPageNumber => EndIndex + 1;
}
enum DetectedPageOrientation
{
    Portrait,
    Landscape
}
Imports IronPrint
Imports IronPdf
Imports System.IO

Await PrintDocumentByOrientationBatchesAsync(documentPath:=documentPath, printerName:=printerName, numberOfCopies:=effectiveCopies)

Private Async Function PrintDocumentByOrientationBatchesAsync(documentPath As String, printerName As String, numberOfCopies As Integer) As Task
    Dim tempFolder = Path.Combine(Path.GetTempPath(), "ironprint-orientation-workaround", Guid.NewGuid().ToString("N"))
    Directory.CreateDirectory(tempFolder)
    Try
        Using pdf = PdfDocument.FromFile(documentPath)
            Dim batches = GetConsecutiveOrientationBatches(pdf)
            ' Since the document is printed in multiple jobs, copies are handled manually
            ' to preserve the full document order per copy.
            For copy = 1 To numberOfCopies
                For Each batch In batches
                    Dim batchPath = Path.Combine(tempFolder, $"copy_{copy}_pages_{batch.StartPageNumber}_{batch.EndPageNumber}_{batch.Orientation}.pdf")
                    Using batchPdf = pdf.CopyPages(batch.StartIndex, batch.EndIndex)
                        batchPdf.SaveAs(batchPath)
                        Dim printSettings = New PrintSettings With {
                            .PrinterName = printerName,
                            .NumberOfCopies = 1,
                            .PaperOrientation = If(batch.Orientation = DetectedPageOrientation.Landscape, PaperOrientation.Landscape, PaperOrientation.Portrait),
                            .PaperSize = PaperSize.PrinterDefault
                        }
                        Await Printer.PrintAsync(batchPath, printSettings)
                        ' Optional delay to help ensure print jobs are queued in order.
                        Await Task.Delay(500)
                    End Using
                Next
            Next
        End Using
    Finally
        Try
            Directory.Delete(tempFolder, recursive:=True)
        Catch
            ' Ignore cleanup errors in case the print spooler is still accessing the files.
        End Try
    End Try
End Function

Private Function GetConsecutiveOrientationBatches(pdf As PdfDocument) As List(Of PageOrientationBatch)
    Dim batches = New List(Of PageOrientationBatch)()
    If pdf.PageCount = 0 Then
        Return batches
    End If
    Dim currentOrientation = GetPageOrientation(pdf.Pages(0).Width, pdf.Pages(0).Height)
    Dim batchStartIndex = 0
    For pageIndex = 1 To pdf.PageCount - 1
        Dim page = pdf.Pages(pageIndex)
        Dim pageOrientation = GetPageOrientation(page.Width, page.Height)
        If pageOrientation <> currentOrientation Then
            batches.Add(New PageOrientationBatch(StartIndex:=batchStartIndex, EndIndex:=pageIndex - 1, Orientation:=currentOrientation))
            batchStartIndex = pageIndex
            currentOrientation = pageOrientation
        End If
    Next
    batches.Add(New PageOrientationBatch(StartIndex:=batchStartIndex, EndIndex:=pdf.PageCount - 1, Orientation:=currentOrientation))
    Return batches
End Function

Private Function GetPageOrientation(width As Double, height As Double) As DetectedPageOrientation
    Return If(width > height, DetectedPageOrientation.Landscape, DetectedPageOrientation.Portrait)
End Function

Private NotInheritable Class PageOrientationBatch
    Public Property StartIndex As Integer
    Public Property EndIndex As Integer
    Public Property Orientation As DetectedPageOrientation

    Public Sub New(StartIndex As Integer, EndIndex As Integer, Orientation As DetectedPageOrientation)
        Me.StartIndex = StartIndex
        Me.EndIndex = EndIndex
        Me.Orientation = Orientation
    End Sub

    Public ReadOnly Property StartPageNumber As Integer
        Get
            Return StartIndex + 1
        End Get
    End Property

    Public ReadOnly Property EndPageNumber As Integer
        Get
            Return EndIndex + 1
        End Get
    End Property
End Class

Private Enum DetectedPageOrientation
    Portrait
    Landscape
End Enum
$vbLabelText   $csharpLabel

GetConsecutiveOrientationBatches produit un PageOrientationBatch par série contiguë, et Printer.PrintAsync exécute chaque plage avec son propre PaperOrientation. Le Task.Delay(500) entre les travaux aide le spooler à les mettre en file d'attente dans l'ordre.

AvertissementChaque plage d'orientation est envoyée sous la forme d'un travail d'impression distinct. Sur une imprimante physique, les travaux sont mis en file d'attente consécutivement, mais avec Microsoft Print to PDF ou une imprimante virtuelle similaire, chaque lot peut demander son propre fichier de sortie.

Curtis Chau
Rédacteur technique

Curtis Chau détient un baccalauréat en informatique (Université de Carleton) et se spécialise dans le développement front-end avec expertise en Node.js, TypeScript, JavaScript et React. Passionné par la création d'interfaces utilisateur intuitives et esthétiquement plaisantes, Curtis aime travailler avec des frameworks modernes ...

Lire la suite
Prêt à commencer?
Nuget Téléchargements 44,923 | Version : 2026.7 vient de sortir
Still Scrolling Icon

Vous faites encore défiler ?

Vous voulez une preuve rapidement ? PM > Install-Package IronPrint
exécuter un échantillon regarder votre document sortir de l'imprimante.