如何使用 IronPDF 在 C# 中將 PDF 圖片轉為平面圖層

使用 C# 將 PDF 文件扁平化

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

IronPDF 能透過 C# 僅需一行程式碼即可將 PDF 文件"扁平化",將互動式表單欄位轉換為靜態內容,以防止後續修改並確保文件完整性。

PDF 文件通常包含互動式表單,其中含有可填寫的元件,例如單選鈕、核取方塊、文字方塊及清單。 若因安全或歸檔需求需將這些文件設為不可編輯,您需要將 PDF 檔案進行扁平化處理。IronPDF 僅需一行程式碼即可提供此功能。 此功能對於處理商業應用程式中的 PDF 表單、法律文件,或任何需要永久保存文件的場景而言,至關重要。

可填寫 PDF 表單橫幅,顯示 Adobe PDF 標誌及兩個帶有輸入欄位的互動式表單範例文件
帶有禁止符號的鉛筆圖示,表示編輯限制或唯讀存取
帶有紅色標題和弧形標誌的 Adobe PDF 檔案圖示

快速入門:一行程式碼簡化您的 PDF 檔案

使用 IronPDF 將 PDF 文件轉為平面格式,以移除所有互動功能,並建立永久且不可編輯的內容。 這段 C# 單行程式碼會載入現有的 PDF 檔案,移除所有可填寫的控件,並儲存受保護的文件。

  1. using NuGet 套件管理員安裝 https://www.nuget.org/packages/IronPdf

    PM > Install-Package IronPdf
  2. 請複製並執行此程式碼片段。

    IronPdf.PdfDocument.FromFile("input.pdf").Flatten().SaveAs("flattened.pdf");
  3. 部署至您的生產環境進行測試

    立即透過免費試用,在您的專案中開始使用 IronPDF

    arrow pointer

如何在 C# 中將 PDF 文件轉換為平面文件?

安裝 IronPDF 後,您只需一行程式碼即可將 PDF 檔案進行扁平化處理。 此流程適用於由 HTML 檔案HTML 字串或現有 PDF 文件所建立的 PDF 檔案。

以下程式碼範例使用 PdfDocument 類別來載入現有的 PDF 檔案。 若需動態產生 PDF,請使用 ChromePdfRenderer 類別。 IronPDF 的 Chrome 渲染引擎可確保在扁平化處理前,精確呈現複雜表單。

若要將 PDF 檔案轉換為平面檔案,請呼叫 Flatten 方法。 此操作將移除所有互動式元件,包括單選鈕、核取方塊及文字欄位,使文件完全無法編輯。

:path=/static-assets/pdf/content-code-examples/how-to/pdf-image-flatten-csharp-flatten-pdf.cs
using IronPdf;

// Select the desired PDF File
PdfDocument pdf = PdfDocument.FromFile("before.pdf");

// Flatten the pdf
pdf.Flatten();

// Save as a new file
pdf.SaveAs("after_flatten.pdf");
using IronPdf;

// Select the desired PDF File
PdfDocument pdf = PdfDocument.FromFile("before.pdf");

// Flatten the pdf
pdf.Flatten();

// Save as a new file
pdf.SaveAs("after_flatten.pdf");
using IronPdf;

// Select the desired PDF File
PdfDocument pdf = PdfDocument.FromFile("before.pdf");

// Flatten the pdf
pdf.Flatten();

// Save as a new file
pdf.SaveAs("after_flatten.pdf");
Imports IronPdf

' Select the desired PDF File
Dim pdf As PdfDocument = PdfDocument.FromFile("before.pdf")

' Flatten the pdf
pdf.Flatten()

' Save as a new file
pdf.SaveAs("after_flatten.pdf")
$vbLabelText   $csharpLabel

針對複雜情境,您可以在扁平化特定頁面之前,先將其扁平化或處理表單資料

using IronPdf;

// Load a PDF with fillable forms
PdfDocument pdf = PdfDocument.FromFile("form-document.pdf");

// Optionally, pre-fill form fields before flattening
pdf.Form.Fields[0].Value = "John Doe";
pdf.Form.Fields[1].Value = "john@example.com";

// Flatten only specific pages (pages 1-3)
pdf.FlattenPagesRange(0, 2);

// Or flatten the entire document
pdf.Flatten();

// Save the result
pdf.SaveAs("flattened-form.pdf");
using IronPdf;

// Load a PDF with fillable forms
PdfDocument pdf = PdfDocument.FromFile("form-document.pdf");

// Optionally, pre-fill form fields before flattening
pdf.Form.Fields[0].Value = "John Doe";
pdf.Form.Fields[1].Value = "john@example.com";

// Flatten only specific pages (pages 1-3)
pdf.FlattenPagesRange(0, 2);

// Or flatten the entire document
pdf.Flatten();

// Save the result
pdf.SaveAs("flattened-form.pdf");
Imports IronPdf

' Load a PDF with fillable forms
Dim pdf As PdfDocument = PdfDocument.FromFile("form-document.pdf")

' Optionally, pre-fill form fields before flattening
pdf.Form.Fields(0).Value = "John Doe"
pdf.Form.Fields(1).Value = "john@example.com"

' Flatten only specific pages (pages 1-3)
pdf.FlattenPagesRange(0, 2)

' Or flatten the entire document
pdf.Flatten()

' Save the result
pdf.SaveAs("flattened-form.pdf")
$vbLabelText   $csharpLabel

如何確認 PDF 是否已扁平化?

以下輸出顯示翻譯前後的對照。 第一個 PDF 檔案包含可編輯的表單欄位。 應用 IronPDF 的 flatten 方法後,文件將完全無法編輯。 此程式碼適用於任何 .NET 專案,包括 ASP.NET 應用程式Blazor 伺服器

請注意使用 Flatten 方法後,表單將無法被偵測。

若要驗證扁平化是否成功,請檢查表單欄位數量:

using IronPdf;

// Load the flattened PDF
PdfDocument flattenedPdf = PdfDocument.FromFile("flattened.pdf");

// Check if any form fields exist
if (flattenedPdf.Form.Fields.Count == 0)
{
    Console.WriteLine("PDF has been successfully flattened - no interactive fields remain.");
}
else
{
    Console.WriteLine($"Warning: {flattenedPdf.Form.Fields.Count} form fields still exist.");
}
using IronPdf;

// Load the flattened PDF
PdfDocument flattenedPdf = PdfDocument.FromFile("flattened.pdf");

// Check if any form fields exist
if (flattenedPdf.Form.Fields.Count == 0)
{
    Console.WriteLine("PDF has been successfully flattened - no interactive fields remain.");
}
else
{
    Console.WriteLine($"Warning: {flattenedPdf.Form.Fields.Count} form fields still exist.");
}
Imports IronPdf

' Load the flattened PDF
Dim flattenedPdf As PdfDocument = PdfDocument.FromFile("flattened.pdf")

' Check if any form fields exist
If flattenedPdf.Form.Fields.Count = 0 Then
    Console.WriteLine("PDF has been successfully flattened - no interactive fields remain.")
Else
    Console.WriteLine($"Warning: {flattenedPdf.Form.Fields.Count} form fields still exist.")
End If
$vbLabelText   $csharpLabel

表單欄位在扁平化後會發生什麼變化?

當您將 PDF 文件"扁平化"時,所有互動式表單元素都會經歷永久性的轉換。 表單欄位會轉換為靜態頁面內容,成為文件視覺層的一部分:

  • 頁面上的文字欄位將轉為一般文字
  • 複選框和單選按鈕將轉為靜態圖片,顯示其選取狀態
  • 下拉式選單僅以純文字顯示所選的值
  • 數位簽章在視覺上得以保留,但會失去加密驗證功能

此操作無法撤銷。 若日後需要編輯功能,請保留原始互動式 PDF 的副本。 對於同時需要安全性與可編輯性的文件,請使用 PDF 權限與密碼設定,而非將文件轉換為純文字格式。

何時該將 PDF 文件進行扁平化處理?

在以下商業情境中,PDF 扁平化處理至關重要:

  1. 法律文件歸檔:在簽署後將合約與協議進行扁平化處理,以防止內容遭竄改並維持法律效力。

  2. 報告分發:在分發前,請將財務報告和數據表與計算欄位整合為單一檔案,以防止篡改。

  3. 表單提交處理:在用戶完成線上表單後,將 PDF 檔案進行扁平化處理,以建立永久記錄。

  4. 列印最佳化:由於印表機不會處理互動式元素,因此"扁平化"的 PDF 檔案能更穩定地列印。

  5. 檔案大小壓縮:透過"扁平化"處理,可在進行 PDF 壓縮時移除表單欄位資料結構,從而縮小檔案大小。

以下是一個用於歸檔多個已填妥表單的批次處理範例:

using IronPdf;
using System.IO;

public class BatchPdfFlattener
{
    public static void FlattenAllPdfsInDirectory(string sourceDir, string outputDir)
    {
        // Ensure output directory exists
        Directory.CreateDirectory(outputDir);

        // Get all PDF files in source directory
        string[] pdfFiles = Directory.GetFiles(sourceDir, "*.pdf");

        foreach (string pdfFile in pdfFiles)
        {
            try
            {
                // Load the PDF
                PdfDocument pdf = PdfDocument.FromFile(pdfFile);

                // Flatten the document
                pdf.Flatten();

                // Save to output directory with "_flattened" suffix
                string fileName = Path.GetFileNameWithoutExtension(pdfFile);
                string outputPath = Path.Combine(outputDir, $"{fileName}_flattened.pdf");
                pdf.SaveAs(outputPath);

                Console.WriteLine($"Flattened: {fileName}");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error processing {pdfFile}: {ex.Message}");
            }
        }
    }
}
using IronPdf;
using System.IO;

public class BatchPdfFlattener
{
    public static void FlattenAllPdfsInDirectory(string sourceDir, string outputDir)
    {
        // Ensure output directory exists
        Directory.CreateDirectory(outputDir);

        // Get all PDF files in source directory
        string[] pdfFiles = Directory.GetFiles(sourceDir, "*.pdf");

        foreach (string pdfFile in pdfFiles)
        {
            try
            {
                // Load the PDF
                PdfDocument pdf = PdfDocument.FromFile(pdfFile);

                // Flatten the document
                pdf.Flatten();

                // Save to output directory with "_flattened" suffix
                string fileName = Path.GetFileNameWithoutExtension(pdfFile);
                string outputPath = Path.Combine(outputDir, $"{fileName}_flattened.pdf");
                pdf.SaveAs(outputPath);

                Console.WriteLine($"Flattened: {fileName}");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error processing {pdfFile}: {ex.Message}");
            }
        }
    }
}
Imports IronPdf
Imports System.IO

Public Class BatchPdfFlattener
    Public Shared Sub FlattenAllPdfsInDirectory(sourceDir As String, outputDir As String)
        ' Ensure output directory exists
        Directory.CreateDirectory(outputDir)

        ' Get all PDF files in source directory
        Dim pdfFiles As String() = Directory.GetFiles(sourceDir, "*.pdf")

        For Each pdfFile As String In pdfFiles
            Try
                ' Load the PDF
                Dim pdf As PdfDocument = PdfDocument.FromFile(pdfFile)

                ' Flatten the document
                pdf.Flatten()

                ' Save to output directory with "_flattened" suffix
                Dim fileName As String = Path.GetFileNameWithoutExtension(pdfFile)
                Dim outputPath As String = Path.Combine(outputDir, $"{fileName}_flattened.pdf")
                pdf.SaveAs(outputPath)

                Console.WriteLine($"Flattened: {fileName}")
            Catch ex As Exception
                Console.WriteLine($"Error processing {pdfFile}: {ex.Message}")
            End Try
        Next
    End Sub
End Class
$vbLabelText   $csharpLabel

有關進階 PDF 處理技術(包括在扁平化後合併或分割 PDF),請參閱 IronPDF 的完整文件。


函式庫快速存取

文件說明

閱讀更多文件

請閱讀文件以瞭解如何將 PDF 檔案扁平化、編輯及處理等更多資訊。

瀏覽 IronPDF 文件

準備好探索更多可能性了嗎? 請點此查看我們的教學頁面:其他功能

常見問題

所謂「將 PDF 扁平化」是指什麼?

PDF 扁平化會將所有互動式表單欄位(如核取方塊、文字方塊和單選鈕)轉換為靜態且不可編輯的內容。IronPDF 提供此功能,以確保文件完整性並防止後續修改。

如何在 C# 中將 PDF 轉換為平面檔案?

using IronPDF,您只需一行程式碼即可將 PDF 文件扁平化:IronPdf.PdfDocument.FromFile("input.pdf").Flatten().SaveAs("flattened.pdf")。此操作會載入 PDF 文件、移除所有互動元素,並儲存已扁平化的文件。

我可以只將特定頁面而非整個文件進行扁平化處理嗎?

是的,IronPDF 允許您使用 FlattenPagesRange 方法將特定頁面扁平化。例如,pdf.FlattenPagesRange(0, 2) 將僅將文件的第 1 至 3 頁扁平化,同時保留其他頁面的互動功能。

哪些類型的表單欄位可以被扁平化?

IronPDF 能將所有互動式元件(包括單選鈕、核取方塊、文字欄位、下拉式清單以及任何其他可填寫的表單元素)轉為平面化內容,並將其轉換為永久的靜態內容。

在將 PDF 轉換為平面檔案前,我可以先填寫表單欄位嗎?

是的,IronPDF 允許您在進行「扁平化」處理前預先填入表單欄位。您可以在呼叫 Flatten 方法之前設定值,例如 pdf.Form.Fields[0].Value = "John Doe",以建立一份已填妥且不可編輯的文件。

PDF 扁平化處理過程使用哪種渲染引擎?

IronPDF 採用 Chrome 渲染引擎,確保在將表單扁平化之前能精確渲染複雜表單,並在整個過程中維持文件的視覺完整性。

為什麼我需要將 PDF 文件轉換為平面檔案?

using IronPDF 將 PDF 文件「扁平化」對於安全性、歸檔用途、法律文件,或任何需要永久保存文件且必須防止表單資料被進一步修改的場景而言,至關重要。

Curtis Chau
技術撰稿人

Curtis Chau 擁有卡爾頓大學(Carleton University)的電腦科學學士學位,專精於前端開發,並精通 Node.js、TypeScript、JavaScript 及 React。他熱衷於打造直觀且美觀的用戶介面,喜歡運用現代框架,並創建結構完善、視覺上吸引人的手冊。

除了開發工作之外,Curtis 對物聯網(IoT)抱有濃厚興趣,致力於探索整合硬體與軟體的創新方法。閒暇時,他喜歡玩遊戲和開發 Discord 機器人,將對科技的熱愛與創意相結合。

準備開始了嗎?
Nuget 下載 19,014,616 | 版本: 2026.5 just released
Still Scrolling Icon

還在往下捲動嗎?

想要快速確認成果嗎? PM > Install-Package IronPdf
執行範例 觀看您的 HTML 轉為 PDF。