使用 C# 更改 PDF 页面大小

更改 PDF 页面大小

Aspose.PDF for .NET 让您可以在 .NET 应用程序中通过简单的代码行更改 PDF 页面大小。 本主题解释了如何更新/更改现有 PDF 文件的页面尺寸(大小)。

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

Page 类包含 SetPageSize(…) 方法,允许您设置页面大小。以下代码片段通过几个简单的步骤更新页面尺寸:

  1. 加载源 PDF 文件。
  2. 将页面获取到 PageCollection 对象中。
  3. 获取指定页面。
  4. 调用 SetPageSize(..) 方法以更新其尺寸。
  5. 调用 Document 类的 Save(..) 方法以生成具有更新页面尺寸的 PDF 文件。

以下代码片段演示如何将 PDF 页面尺寸更改为 A4 大小。

// For complete examples and data files, visit https://github.com/aspose-pdf/Aspose.PDF-for-.NET
private static void ChangePdfPageSize()
{
    // The path to the documents directory
    var dataDir = RunExamples.GetDataDir_AsposePdf_Pages();

    // Open PDF document
    using (var document = new Aspose.Pdf.Document(dataDir + "UpdateDimensions.pdf"))
    {
        // Get page collection
        var pageCollection = document.Pages;
        // Get particular page
        var pdfPage = pageCollection[1];
        // Set the page size as A4 (11.7 x 8.3 in) and in Aspose.Pdf, 1 inch = 72 points
        // So A4 dimensions in points will be (842.4, 597.6)
        pdfPage.SetPageSize(597.6, 842.4);
        // Save PDF document
        document.Save(dataDir + "UpdateDimensions_out.pdf"); 
    }
}

获取 PDF 页面大小

您可以使用 Aspose.PDF for .NET 读取现有 PDF 文件的页面大小。以下代码示例演示了如何使用 C# 读取 PDF 页面尺寸。

// For complete examples and data files, visit https://github.com/aspose-pdf/Aspose.PDF-for-.NET
private static void GetPdfPageSize()
{
    // The path to the documents directory
    var dataDir = RunExamples.GetDataDir_AsposePdf_Pages();
    
    // Open PDF document
    using (var document = new Aspose.Pdf.Document(dataDir + "UpdateDimensions.pdf"))
    {
        // Adds a blank page to pdf document
        Page page = document.Pages.Count > 0 ? document.Pages[1] : document.Pages.Add();
        // Get page height and width information
        Console.WriteLine(page.GetPageRect(true).Width.ToString() + ":" + page.GetPageRect(true).Height);
        // Rotate page at 90 degree angle
        page.Rotate = Rotation.on90;
        // Get page height and width information
        Console.WriteLine(page.GetPageRect(true).Width.ToString() + ":" + page.GetPageRect(true).Height);
    }
}