Faire pivoter les pages PDF en utilisant C#

Ce sujet décrit comment mettre à jour ou changer l’orientation des pages dans un fichier PDF existant par programmation avec C#.

Le code suivant fonctionne également avec la bibliothèque Aspose.PDF.Drawing.

Changer l’orientation de la page

Depuis la version Aspose.PDF for .NET 9.6.0, nous avons ajouté de nouvelles fonctionnalités intéressantes comme le changement de l’orientation de la page du paysage au portrait et vice versa. Pour changer l’orientation de la page, définissez le MediaBox de la page en utilisant le code suivant. Vous pouvez également changer l’orientation de la page en définissant l’angle de rotation en utilisant la méthode Rotate().

// For complete examples and data files, visit https://github.com/aspose-pdf/Aspose.PDF-for-.NET
private static void ChangePageOrientation()
{
    // The path to the documents directory
    var dataDir = RunExamples.GetDataDir_AsposePdf_Pages();
    
    // Open PDF document
    using (var document = new Aspose.Pdf.Document(dataDir + "RotatePagesInput.pdf"))
    {
        foreach (Page page in document.Pages)
        {
            Aspose.Pdf.Rectangle r = page.MediaBox;
            double newHeight = r.Width;
            double newWidth = r.Height;
            double newLLX = r.LLX;
            //  We must to move page upper in order to compensate changing page size
            // (lower edge of the page is 0,0 and information is usually placed from the
            //  Top of the page. That's why we move lover edge upper on difference between
            //  Old and new height.
            double newLLY = r.LLY + (r.Height - newHeight);
            page.MediaBox = new Aspose.Pdf.Rectangle(newLLX, newLLY, newLLX + newWidth, newLLY + newHeight);
            // Sometimes we also need to set CropBox (if it was set in original file)
            page.CropBox = new Aspose.Pdf.Rectangle(newLLX, newLLY, newLLX + newWidth, newLLY + newHeight);
            // Setting Rotation angle of page
            page.Rotate = Rotation.on90;
        }
        // Save PDF document
        document.Save(dataDir + "ChangeOrientation_out.pdf");
    }
}