C#でPDFページサイズを変更する

C#で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ファイルの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);
    }
}