如何在C#中使用IronPDF拆分多頁PDF

將多頁PDF在C#中拆分為單頁文件

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

IronPDF使您能夠使用CopyPage方法將多頁PDF文件拆分為單個的單頁PDF。 這種方法允許開發者迭代每一頁,並用幾行程式碼將它們保存為單獨的文件。 無論您是在處理掃描文件、報告還是任何多頁PDF,IronPDF都為文件管理和處理任務提供了一個高效的解決方案。

當您需要將單個頁面分發給不同的接收者、單獨處理頁面或與需要單頁輸入的文件管理系統整合時,PDF拆分功能特別有用。 IronPDF的強大Chrome渲染引擎確保您拆分的頁面保持其原始格式、圖像和文字質量。

快速入門:將多頁PDF拆分為單頁

快速開始使用IronPDF將多頁PDF拆分為單頁文件。 通過使用CopyPage方法,您可以有效率地迭代PDF的每一頁,並將它們保存為單獨的文件。 這個簡化的過程非常適合尋求快速和可靠的PDF文件管理解決方案的開發者。 首先,確保您已經通過NuGet安裝了IronPDF

  1. 使用NuGet套件管理器安裝https://www.nuget.org/packages/IronPdf

    PM > Install-Package IronPdf
  2. 複製並運行這段程式碼片段。

    var pdf = new IronPdf.PdfDocument("multipage.pdf");
    for (int i = 0; i < pdf.PageCount; i++) {
      var singlePagePdf = pdf.CopyPage(i);
      singlePagePdf.SaveAs($"page_{i + 1}.pdf");
    }
  3. 部署以在您的實時環境中測試

    今天就開始在您的專案中使用IronPDF,透過免費試用

    arrow pointer

拆分PDF文件

  • 安裝IronPDF程式庫
  • 將多頁PDF拆分為單頁文件
Icon Quote related to 將多頁PDF在C#中拆分為單頁文件

我最喜歡的程式庫是IronPDF。它允許快速高效地操作PDF文件。它還有許多有價值的功能,例如導出到PDF/A格式和數位簽署PDF文件。

Milan Jovanovic related to 將多頁PDF在C#中拆分為單頁文件

Milan Jovanovic

Microsoft MVP

查看案例研究
Icon Quote related to 將多頁PDF在C#中拆分為單頁文件

IronOCR意味著我們每年可以從手動處理中節省$40,000,同時提高生產力,釋放資源以進行高影響的任務。我會強烈推薦它。

Brent Matzelle related to 將多頁PDF在C#中拆分為單頁文件

Brent Matzelle

首席技術官,OPYN

查看案例研究
Icon Quote related to 將多頁PDF在C#中拆分為單頁文件

IronSuite在我們的運營中扮演著至關重要的角色。這些工具增加了包括建立平面圖和改善庫存管理在內的業務效率。

David Jones related to 將多頁PDF在C#中拆分為單頁文件

David Jones

首席軟體工程師,Agorus Build

查看案例研究

如何拆分多頁PDF?

為什麼使用CopyPage方法進行PDF拆分?

CopyPage現在您已擁有IronPDF,您可以將多頁文件拆分為單頁文件。 多頁PDF拆分的概念是使用CopyPages方法複製單個或多個頁面。 這些方法建立新的PdfDocument實例,其中只包含指定的頁面,並保留所有格式、註釋和互動元素。

CopyPage方法是IronPDF中PDF拆分操作的基石。 與其他需要複雜操作或可能導致資料丟失的方法不同,CopyPage建立一個指定頁面的精確副本,保留所有視覺元素、文字格式和嵌入資源。 這使其在文件完整性至關重要的情境,諸如法律文件、發票或存檔記錄中特別理想。

拆分每頁的步驟是什麼?

CopyPages

對於更高級別的場景,您可能需要實施錯誤處理並自訂輸出格式。 以下是包含驗證和自定義命名的綜合範例:

using IronPdf;
using System;
using System.IO;

public class PdfSplitter
{
    public static void SplitPdfWithValidation(string inputPath, string outputDirectory)
    {
        try
        {
            // Validate input file exists
            if (!File.Exists(inputPath))
            {
                throw new FileNotFoundException("Input PDF file not found.", inputPath);
            }

            // Create output directory if it doesn't exist
            Directory.CreateDirectory(outputDirectory);

            // Load the PDF document
            PdfDocument pdf = PdfDocument.FromFile(inputPath);

            // Get the file name without extension for naming split files
            string baseFileName = Path.GetFileNameWithoutExtension(inputPath);

            Console.WriteLine($"Splitting {pdf.PageCount} pages from {baseFileName}...");

            for (int idx = 0; idx < pdf.PageCount; idx++)
            {
                // Copy individual page
                PdfDocument singlePagePdf = pdf.CopyPage(idx);

                // Create descriptive filename with zero-padding for proper sorting
                string pageNumber = (idx + 1).ToString().PadLeft(3, '0');
                string outputPath = Path.Combine(outputDirectory, $"{baseFileName}_Page_{pageNumber}.pdf");

                // Save the single page PDF
                singlePagePdf.SaveAs(outputPath);

                Console.WriteLine($"Created: {outputPath}");
            }

            Console.WriteLine("PDF splitting completed successfully!");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error splitting PDF: {ex.Message}");
            throw;
        }
    }
}
using IronPdf;
using System;
using System.IO;

public class PdfSplitter
{
    public static void SplitPdfWithValidation(string inputPath, string outputDirectory)
    {
        try
        {
            // Validate input file exists
            if (!File.Exists(inputPath))
            {
                throw new FileNotFoundException("Input PDF file not found.", inputPath);
            }

            // Create output directory if it doesn't exist
            Directory.CreateDirectory(outputDirectory);

            // Load the PDF document
            PdfDocument pdf = PdfDocument.FromFile(inputPath);

            // Get the file name without extension for naming split files
            string baseFileName = Path.GetFileNameWithoutExtension(inputPath);

            Console.WriteLine($"Splitting {pdf.PageCount} pages from {baseFileName}...");

            for (int idx = 0; idx < pdf.PageCount; idx++)
            {
                // Copy individual page
                PdfDocument singlePagePdf = pdf.CopyPage(idx);

                // Create descriptive filename with zero-padding for proper sorting
                string pageNumber = (idx + 1).ToString().PadLeft(3, '0');
                string outputPath = Path.Combine(outputDirectory, $"{baseFileName}_Page_{pageNumber}.pdf");

                // Save the single page PDF
                singlePagePdf.SaveAs(outputPath);

                Console.WriteLine($"Created: {outputPath}");
            }

            Console.WriteLine("PDF splitting completed successfully!");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error splitting PDF: {ex.Message}");
            throw;
        }
    }
}
Imports IronPdf
Imports System
Imports System.IO

Public Class PdfSplitter
    Public Shared Sub SplitPdfWithValidation(inputPath As String, outputDirectory As String)
        Try
            ' Validate input file exists
            If Not File.Exists(inputPath) Then
                Throw New FileNotFoundException("Input PDF file not found.", inputPath)
            End If

            ' Create output directory if it doesn't exist
            Directory.CreateDirectory(outputDirectory)

            ' Load the PDF document
            Dim pdf As PdfDocument = PdfDocument.FromFile(inputPath)

            ' Get the file name without extension for naming split files
            Dim baseFileName As String = Path.GetFileNameWithoutExtension(inputPath)

            Console.WriteLine($"Splitting {pdf.PageCount} pages from {baseFileName}...")

            For idx As Integer = 0 To pdf.PageCount - 1
                ' Copy individual page
                Dim singlePagePdf As PdfDocument = pdf.CopyPage(idx)

                ' Create descriptive filename with zero-padding for proper sorting
                Dim pageNumber As String = (idx + 1).ToString().PadLeft(3, "0"c)
                Dim outputPath As String = Path.Combine(outputDirectory, $"{baseFileName}_Page_{pageNumber}.pdf")

                ' Save the single page PDF
                singlePagePdf.SaveAs(outputPath)

                Console.WriteLine($"Created: {outputPath}")
            Next

            Console.WriteLine("PDF splitting completed successfully!")
        Catch ex As Exception
            Console.WriteLine($"Error splitting PDF: {ex.Message}")
            Throw
        End Try
    End Sub
End Class
$vbLabelText   $csharpLabel

頁面迭代如何工作?

PdfDocument物件中。 最後,每頁按順序命名另存為新文件。 迭代過程簡單且高效,因為IronPDF在內部處理解所有複雜的PDF結構操作。

PageCount屬性提供文件中的總頁數,讓您可以安全地迭代而不用擔心超出索引範圍的例外。 每次迭代建立一個完全獨立的PDF文件,意味著您可以單獨處理、修改或分發每一頁,而不影響原始文件或其他拆分頁面。 這種方法在處理大型文件時特別有益,尤其是在您需要提取特定頁面或並行處理頁面時。

什麼時候應該使用CopyPage

儘管CopyPages方法,適用於需要提取多個連續或不連續頁面的情境。 這在您希望建立包含特定頁碼範圍而非單個頁面的PDF文件時特別有用:

using IronPdf;
using System.Collections.Generic;

public class MultiPageExtraction
{
    public static void ExtractPageRanges(string inputPath)
    {
        PdfDocument pdf = PdfDocument.FromFile(inputPath);

        // Extract pages 1-5 (0-indexed, so pages 0-4)
        List<int> firstChapter = new List<int> { 0, 1, 2, 3, 4 };
        PdfDocument chapterOne = pdf.CopyPages(firstChapter);
        chapterOne.SaveAs("Chapter_1.pdf");

        // Extract every other page (odd pages)
        List<int> oddPages = new List<int>();
        for (int i = 0; i < pdf.PageCount; i += 2)
        {
            oddPages.Add(i);
        }
        PdfDocument oddPagesDoc = pdf.CopyPages(oddPages);
        oddPagesDoc.SaveAs("Odd_Pages.pdf");

        // Extract specific non-consecutive pages
        List<int> selectedPages = new List<int> { 0, 4, 9, 14 }; // Pages 1, 5, 10, 15
        PdfDocument customSelection = pdf.CopyPages(selectedPages);
        customSelection.SaveAs("Selected_Pages.pdf");
    }
}
using IronPdf;
using System.Collections.Generic;

public class MultiPageExtraction
{
    public static void ExtractPageRanges(string inputPath)
    {
        PdfDocument pdf = PdfDocument.FromFile(inputPath);

        // Extract pages 1-5 (0-indexed, so pages 0-4)
        List<int> firstChapter = new List<int> { 0, 1, 2, 3, 4 };
        PdfDocument chapterOne = pdf.CopyPages(firstChapter);
        chapterOne.SaveAs("Chapter_1.pdf");

        // Extract every other page (odd pages)
        List<int> oddPages = new List<int>();
        for (int i = 0; i < pdf.PageCount; i += 2)
        {
            oddPages.Add(i);
        }
        PdfDocument oddPagesDoc = pdf.CopyPages(oddPages);
        oddPagesDoc.SaveAs("Odd_Pages.pdf");

        // Extract specific non-consecutive pages
        List<int> selectedPages = new List<int> { 0, 4, 9, 14 }; // Pages 1, 5, 10, 15
        PdfDocument customSelection = pdf.CopyPages(selectedPages);
        customSelection.SaveAs("Selected_Pages.pdf");
    }
}
Imports IronPdf
Imports System.Collections.Generic

Public Class MultiPageExtraction
    Public Shared Sub ExtractPageRanges(inputPath As String)
        Dim pdf As PdfDocument = PdfDocument.FromFile(inputPath)

        ' Extract pages 1-5 (0-indexed, so pages 0-4)
        Dim firstChapter As New List(Of Integer) From {0, 1, 2, 3, 4}
        Dim chapterOne As PdfDocument = pdf.CopyPages(firstChapter)
        chapterOne.SaveAs("Chapter_1.pdf")

        ' Extract every other page (odd pages)
        Dim oddPages As New List(Of Integer)()
        For i As Integer = 0 To pdf.PageCount - 1 Step 2
            oddPages.Add(i)
        Next
        Dim oddPagesDoc As PdfDocument = pdf.CopyPages(oddPages)
        oddPagesDoc.SaveAs("Odd_Pages.pdf")

        ' Extract specific non-consecutive pages
        Dim selectedPages As New List(Of Integer) From {0, 4, 9, 14} ' Pages 1, 5, 10, 15
        Dim customSelection As PdfDocument = pdf.CopyPages(selectedPages)
        customSelection.SaveAs("Selected_Pages.pdf")
    End Sub
End Class
$vbLabelText   $csharpLabel

CopyPages方法非常適合用於建立自定義編輯、提取特定部分或重新組織文件內容。 與多次調用CopyPage相比,這更有效率,當您需要多個頁面時,因為它在一個調用中完成操作。 對於全面的PDF操作能力,您可以將拆分與合併操作組合起來,建立一個複雜的文件工作流程。

準備好瞭解您還可以做什麼嗎? 查看我們的教程頁面:整理PDF。 您也可以探索如何在拆分的PDF中新增頁碼或了解如何管理PDF元資料以增強您的文件管理工作流程。 欲知進階PDF操作技術,請存取我們的完整API參考

常見問題

如何在C#中將多頁PDF拆分為單頁PDF?

您可以使用IronPDF的CopyPage方法拆分多頁PDF。只需載入您的PDF文件,使用for迴圈遍歷每一頁,然後將每一頁保存為單獨的文件。IronPDF使這一過程變得簡單,只需幾行程式碼即可完成,同時保持所有原始格式和質量。

我應該使用哪種方法從PDF中提取單個頁面?

IronPDF提供了CopyPage方法用於從PDF文件中提取單個頁面。該方法可以建立指定頁面的精確副本作為新的PdfDocument實例,保留原文件中的所有格式、註釋和交互元素。

拆分PDF是否能夠保持原始格式和質量?

是的,當您使用IronPDF的CopyPage方法拆分PDF時,所有的視覺元素、文字格式、嵌入資源以及交互元素都將被保留。IronPDF的Chrome渲染引擎確保您的拆分頁面保持其原始格式、圖像和文字質量。

我可以一次拆分多個頁面而不是每次一頁嗎?

是的,IronPDF不僅提供用於單頁的CopyPage,還提供用於多頁的CopyPages方法。CopyPages方法允許您一次性將多個頁面提取為新的PdfDocument實例,為各種拆分方案提供靈活性。

拆分PDF文件的常見使用案例有哪些?

IronPDF的拆分功能非常適合將單個頁面分發給不同的接收者、單獨處理頁面、與需要單頁輸入的文件管理系統整合以及處理法律文件、發票或需保持文件完整性的存檔記錄。

Curtis Chau
技術作家

Curtis Chau擁有Carleton大學的電腦科學學士學位,專精於前端開發,擁有Node.js、TypeScript、JavaScript和React的專業知識。Curtis熱衷於建立直觀且美觀的使用者介面,喜愛使用現代框架並建立結構良好、視覺吸引力的手冊。

除了開發,Curtis對物聯網(IoT)有濃厚的興趣,探索創新的方法來整合硬體和軟體。在空閒時間,他喜歡玩遊戲和建立Discord機器人,結合他對技術的熱愛與創造力。

準備開始了嗎?
Nuget 下載 20,088,359 | 版本: 2026.7 剛剛發布
Still Scrolling Icon

還在捲動嗎?

想快速獲得證明嗎? PM > Install-Package IronPdf
執行範例 看您的HTML變成PDF。