使用 C# 旋转 PDF 页面

本主题描述了如何使用 C# 程序化地更新或更改现有 PDF 文件中页面的方向。

以下代码片段也适用于 Aspose.PDF.Drawing 库。

更改页面方向

从 Aspose.PDF for .NET 9.6.0 版本开始,我们添加了很棒的新功能,例如将页面方向从横向更改为纵向,反之亦然。要更改页面方向,请使用以下代码片段设置页面的 MediaBox。您还可以通过使用 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");
    }
}