如何在 C# 中編輯 PDF

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

Iron Software 已將各種 PDF 編輯功能簡化為 IronPDF 庫中易於理解的方法。 無論是新增簽名、新增 HTML 頁尾、新增浮水印或新增註解。 IronPDF 是您的理想工具,它能讓您擁有可讀的程式碼、程式化的 PDF 產生、輕鬆的調試功能,並能無縫部署到任何受支援的環境或平台。

IronPDF擁有眾多PDF編輯功能。 在本教學文章中,我們將介紹一些主要功能,並提供程式碼範例和解釋。

透過本文,您將很好地了解如何使用 IronPDF 在 C# 中編輯 PDF。

快速入門:幾秒鐘內編輯您的 PDF 檔案

使用 IronPDF,您可以輕鬆地在 C# 中編輯 PDF 文件。 本快速指南將向您展示如何在現有 PDF 檔案中新增文字圖章。只需幾行程式碼,即可修改 PDF 檔案並立即儲存變更。 非常適合需要快速且有效率 PDF 編輯解決方案的開發人員。

Nuget Icon立即開始使用 NuGet 建立 PDF 檔案:

  1. 使用 NuGet 套件管理器安裝 IronPDF

    PM > Install-Package IronPdf

  2. 複製並運行這段程式碼。

    var pdf = IronPdf.PdfDocument.FromFile("example.pdf");
    pdf.ApplyStamp(new IronPdf.Editing.TextStamper("Confidential"));
    pdf.SaveAs("edited_example.pdf");
  3. 部署到您的生產環境進行測試

    立即開始在您的專案中使用 IronPDF,免費試用!
    arrow pointer

目錄

-編輯文檔結構 -存取 PDF DOM 對象 -儲存和匯出 PDF 文檔 -從記憶體載入 PDF 文件 -將 PDF 檔案匯出到內存 -編輯文檔屬性 -使用 C# 解析 PDF 提取文字和圖像 -編輯文字和區域 -替換 PDF 中的文字 -增強 PDF 設計 -新增和編輯註釋 -印章文字和圖像 -自訂浮水印 背景與前景 -繪製文字和點陣圖 -畫線和矩形 -旋轉文字和頁面 -轉換 PDF 頁面

立即開始在您的項目中使用 IronPDF 並免費試用。

第一步:
green arrow pointer
!{--010011000100100101000010010100100100000101010010010110010101111101001110010101010101010101010101010101010101010 0100010111110100100101001101010100010000010100110001001100010111110100001001001100010011110010101010

編輯文檔結構

存取 PDF DOM 對象

操作和存取 PDF 物件既快速又簡單。 IronPDF 簡化了開發人員與 DOM 物件互動的方式,使他們熟悉如何操作網頁的 DOM,從而允許開發人員以程式設計方式存取和操作各種元素,例如文字。

:path=/static-assets/pdf/content-code-examples/how-to/access-pdf-dom-object.cs
using IronPdf;
using System.Linq;

// Instantiate Renderer
ChromePdfRenderer renderer = new ChromePdfRenderer();

// Create a PDF from a URL
PdfDocument pdf = renderer.RenderUrlAsPdf("https://ironpdf.com/");

// Access DOM Objects
var objects = pdf.Pages.First().ObjectModel;
Imports IronPdf
Imports System.Linq

' Instantiate Renderer
Private renderer As New ChromePdfRenderer()

' Create a PDF from a URL
Private pdf As PdfDocument = renderer.RenderUrlAsPdf("https://ironpdf.com/")

' Access DOM Objects
Private objects = pdf.Pages.First().ObjectModel
$vbLabelText   $csharpLabel

有關此程式碼片段的更詳細解釋以及探索其附加功能,請參閱我們的綜合操作指南

儲存和匯出文檔

為了保存和匯出文檔,IronPDF 允許使用者快速將編輯後的文檔PdfDocument.SaveAs儲存到磁碟,同時還允許匯出為其他格式,例如二進位資料和記憶體流。

有關此程式碼片段的更詳細解釋以及探索其附加功能,請參閱我們的綜合操作指南

從記憶體載入 PDF

IronPDF 與現有的 C# .NET 應用程式完美整合; 我們可以透過MemoryStream物件從 MemoryStream 載入和建立 PDF 檔案。

:path=/static-assets/pdf/content-code-examples/how-to/pdf-memory-stream-from-stream.cs
using IronPdf;
using System.IO;

// Read PDF file as stream
var fileByte = File.ReadAllBytes("sample.pdf");

// Instantiate PDF object from stream
PdfDocument pdf = new PdfDocument(fileByte);
Imports IronPdf
Imports System.IO

' Read PDF file as stream
Private fileByte = File.ReadAllBytes("sample.pdf")

' Instantiate PDF object from stream
Private pdf As New PdfDocument(fileByte)
$vbLabelText   $csharpLabel

有關此程式碼片段的更詳細解釋以及探索其附加功能,請參閱我們的綜合操作指南

將 PDF 文件匯出到內存

同樣,我們也可以透過MemoryStream物件將 PDF 匯出到 C# .NET 中的 MemoryStream。

:path=/static-assets/pdf/content-code-examples/how-to/pdf-to-memory-stream-to-stream.cs
using IronPdf;
using System.IO;

var renderer = new ChromePdfRenderer();

// Convert the URL into PDF
PdfDocument pdf = renderer.RenderUrlAsPdf("https://ironpdf.com/");

// Export PDF as Stream
MemoryStream pdfAsStream = pdf.Stream;

// Export PDF as Byte Array
byte[] pdfAsByte = pdf.BinaryData;
Imports IronPdf
Imports System.IO

Private renderer = New ChromePdfRenderer()

' Convert the URL into PDF
Private pdf As PdfDocument = renderer.RenderUrlAsPdf("https://ironpdf.com/")

' Export PDF as Stream
Private pdfAsStream As MemoryStream = pdf.Stream

' Export PDF as Byte Array
Private pdfAsByte() As Byte = pdf.BinaryData
$vbLabelText   $csharpLabel

有關此程式碼片段的更詳細解釋以及探索其附加功能,請參閱我們的綜合操作指南

編輯文檔文本

用 C# 解析 PDF

使用 IronPDF 從 PDF 中提取文字既快速又簡單。 只需使用ExtractAllText方法即可提取每一頁中的所有文本,讓您輕鬆存取和使用文件內容。 這項強大的功能可以提高工作效率並簡化您的工作流程!

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

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

// Extract all text from an pdf
string allText = pdf.ExtractAllText();

// Extract all text from page 1
string page1Text = pdf.ExtractTextFromPage(0);
Imports IronPdf

' Select the desired PDF File
Private pdf As PdfDocument = PdfDocument.FromFile("sample.pdf")

' Extract all text from an pdf
Private allText As String = pdf.ExtractAllText()

' Extract all text from page 1
Private page1Text As String = pdf.ExtractTextFromPage(0)
$vbLabelText   $csharpLabel

有關此程式碼片段的更詳細解釋以及探索其附加功能,請參閱我們的綜合操作指南

提取文字和圖像

使用 IronPDF,您不僅限於提取文本,還可以非常輕鬆地從 PDF 中提取圖像! 使用ExtractAllImages功能,您可以快速擷取所需的所有影像。

:path=/static-assets/pdf/content-code-examples/how-to/extract-text-and-images-extract-image.cs
using IronPdf;

PdfDocument pdf = PdfDocument.FromFile("sample.pdf");

// Extract images
var images = pdf.ExtractAllImages();

for(int i = 0; i < images.Count; i++)
{
    // Export the extracted images
    images[i].SaveAs($"images/image{i}.png");
}
Imports IronPdf

Private pdf As PdfDocument = PdfDocument.FromFile("sample.pdf")

' Extract images
Private images = pdf.ExtractAllImages()

For i As Integer = 0 To images.Count - 1
	' Export the extracted images
	images(i).SaveAs($"images/image{i}.png")
Next i
$vbLabelText   $csharpLabel

有關此程式碼片段的更詳細解釋以及探索其附加功能,請參閱我們的綜合操作指南

編輯文字和區域

在我們需要透過編輯來保護敏感資訊的情況下,我們有一個強大的工具可以隨時使用: RedactTextonAllPages 。 借助此功能,我們可以輕鬆識別並隱藏整個 PDF 中特定關鍵字的每一個實例。 這是一種有效的方式,既能確保機密資訊受到保護,又能讓我們放心地分享文件。

:path=/static-assets/pdf/content-code-examples/how-to/redact-text-redact-text.cs
using IronPdf;

PdfDocument pdf = PdfDocument.FromFile("novel.pdf");

// Redact 'Alaric' phrase from all pages
pdf.RedactTextOnAllPages("Alaric");

pdf.SaveAs("redacted.pdf");
Imports IronPdf

Private pdf As PdfDocument = PdfDocument.FromFile("novel.pdf")

' Redact 'Alaric' phrase from all pages
pdf.RedactTextOnAllPages("Alaric")

pdf.SaveAs("redacted.pdf")
$vbLabelText   $csharpLabel

有關此程式碼片段的更詳細解釋以及探索其附加功能,請參閱我們的綜合操作指南

替換PDF中的文本

若要使用 IronPDF 增強 PDF 文檔,您可以輕鬆地替換整個文件中的文字。透過使用ReplaceTextonAllPages功能,您可以提供需要替換的oldText文字以及要取代它的newText 。 此方法可以有效率地更新文件中所有oldText實例,確保文件外觀一致且專業。

:path=/static-assets/pdf/content-code-examples/how-to/find-replace-text-all-page.cs
using IronPdf;

ChromePdfRenderer renderer = new ChromePdfRenderer();

PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>.NET6</h1>");

string oldText = ".NET6";
string newText = ".NET7";

// Replace text on all pages
pdf.ReplaceTextOnAllPages(oldText, newText);

pdf.SaveAs("replaceText.pdf");
Imports IronPdf

Private renderer As New ChromePdfRenderer()

Private pdf As PdfDocument = renderer.RenderHtmlAsPdf("<h1>.NET6</h1>")

Private oldText As String = ".NET6"
Private newText As String = ".NET7"

' Replace text on all pages
pdf.ReplaceTextOnAllPages(oldText, newText)

pdf.SaveAs("replaceText.pdf")
$vbLabelText   $csharpLabel

有關此程式碼片段的更詳細解釋以及探索其附加功能,請參閱我們的綜合操作指南

增強型 PDF 設計

新增和編輯註釋

IronPDF 為 PDF 註釋提供了豐富的自訂選項,讓使用者可以直接在 PDF 頁面中新增"便條"註解。 透過TextAnnotation類,可以以程式設計方式新增註釋,並提供諸如調整大小、透明度、圖示選擇和編輯功能等進階選項。

:path=/static-assets/pdf/content-code-examples/how-to/annotation-add-annotation.cs
using IronPdf;
using IronPdf.Annotations;

ChromePdfRenderer renderer = new ChromePdfRenderer();
PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>Annotation</h1>");

// Create a PDF annotation object on a specified page index
TextAnnotation annotation = new TextAnnotation(0)
{
    Title = "This is the title",
    Contents = "This is the long 'sticky note' comment content...",
    X = 50,
    Y = 700,
};

// Add the annotation
pdf.Annotations.Add(annotation);
pdf.SaveAs("annotation.pdf");
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

有關此程式碼片段的更詳細解釋以及探索其附加功能,請參閱我們的綜合操作指南

印章文字和圖像

IronPDF 提供了豐富的選項,可以自訂如何在 PDF 上添加文字和圖像。 在這個例子中,我們將使用TextStamper類,透過ApplyStamp方法將圖章應用在 PDF 上,如下所示。

:path=/static-assets/pdf/content-code-examples/how-to/stamp-text-image-stamp-text.cs
using IronPdf;
using IronPdf.Editing;

ChromePdfRenderer renderer = new ChromePdfRenderer();

PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>Example HTML Document!</h1>");

// Create text stamper
TextStamper textStamper = new TextStamper()
{
    Text = "Text Stamper!",
    FontFamily = "Bungee Spice",
    UseGoogleFont = true,
    FontSize = 30,
    IsBold = true,
    IsItalic = true,
    VerticalAlignment = VerticalAlignment.Top,
};

// Stamp the text stamper
pdf.ApplyStamp(textStamper);

pdf.SaveAs("stampText.pdf");
Imports IronPdf
Imports IronPdf.Editing

Private renderer As New ChromePdfRenderer()

Private pdf As PdfDocument = renderer.RenderHtmlAsPdf("<h1>Example HTML Document!</h1>")

' Create text stamper
Private textStamper As New TextStamper() With {
	.Text = "Text Stamper!",
	.FontFamily = "Bungee Spice",
	.UseGoogleFont = True,
	.FontSize = 30,
	.IsBold = True,
	.IsItalic = True,
	.VerticalAlignment = VerticalAlignment.Top
}

' Stamp the text stamper
pdf.ApplyStamp(textStamper)

pdf.SaveAs("stampText.pdf")
$vbLabelText   $csharpLabel

有關此程式碼片段的更詳細解釋以及探索其附加功能,請參閱我們的綜合操作指南

自訂浮水印

我們還可以使用ApplyWatermark方法將浮水印無縫整合到新渲染的 PDF 和現有文件中。 此功能可增強品牌認知度,確保您的宣傳資料傳達專業形象。

:path=/static-assets/pdf/content-code-examples/how-to/custom-watermark-apply-watermark.cs
using IronPdf;

string watermarkHtml = @"
<img src='https://ironsoftware.com/img/products/ironpdf-logo-text-dotnet.svg'>
<h1>Iron Software</h1>";

ChromePdfRenderer renderer = new ChromePdfRenderer();

PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>Watermark</h1>");

// Apply watermark
pdf.ApplyWatermark(watermarkHtml);

pdf.SaveAs("watermark.pdf");
Imports IronPdf

Private watermarkHtml As String = "
<img src='https://ironsoftware.com/img/products/ironpdf-logo-text-dotnet.svg'>
<h1>Iron Software</h1>"

Private renderer As New ChromePdfRenderer()

Private pdf As PdfDocument = renderer.RenderHtmlAsPdf("<h1>Watermark</h1>")

' Apply watermark
pdf.ApplyWatermark(watermarkHtml)

pdf.SaveAs("watermark.pdf")
$vbLabelText   $csharpLabel

有關此程式碼片段的更詳細解釋以及探索其附加功能,請參閱我們的綜合操作指南

背景與前景

除了浮水印和圖章之外,我們還可以使用AddBackgroundPdf為 PDF 添加背景,從而完全自訂您的 PDF。

:path=/static-assets/pdf/content-code-examples/how-to/background-foreground-background.cs
using IronPdf;

ChromePdfRenderer renderer = new ChromePdfRenderer();

PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>Main HTML content</h1>");

// Render background
PdfDocument background = renderer.RenderHtmlAsPdf("<body style='background-color: cyan;'></body>");

// Add background
pdf.AddBackgroundPdf(background);

pdf.SaveAs("addBackground.pdf");
Imports IronPdf

Private renderer As New ChromePdfRenderer()

Private pdf As PdfDocument = renderer.RenderHtmlAsPdf("<h1>Main HTML content</h1>")

' Render background
Private background As PdfDocument = renderer.RenderHtmlAsPdf("<body style='background-color: cyan;'></body>")

' Add background
pdf.AddBackgroundPdf(background)

pdf.SaveAs("addBackground.pdf")
$vbLabelText   $csharpLabel

有關此程式碼片段的更詳細解釋以及探索其附加功能,請參閱我們的綜合操作指南

繪製文字和點陣圖

在PDF上繪製文字既直觀又簡單; 我們使用DrawText並為其提供必要的參數。 在這個例子中,我們添加了新短語Some text字體為 Times New Roman。

:path=/static-assets/pdf/content-code-examples/how-to/draw-text-and-bitmap-draw-text.cs
using IronPdf;
using IronSoftware.Drawing;

ChromePdfRenderer renderer = new ChromePdfRenderer();
PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>testing</h1>");

// Draw text on PDF
pdf.DrawText("Some text", FontTypes.TimesNewRoman.Name, FontSize: 12, PageIndex: 0, X: 100, Y: 100, Color.Black, Rotation: 0);

pdf.SaveAs("drawText.pdf");
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

有關此程式碼片段的更詳細解釋以及探索其附加功能,請參閱我們的綜合操作指南

畫線和矩形

IronPDF 也支援在 PDF 上繪製線條。 我們首先透過初始化兩個PointF類別來建立起點和終點,然後使用DrawLine方法應用它們,如下所示。

:path=/static-assets/pdf/content-code-examples/how-to/draw-line-and-rectangle-draw-line.cs
using IronPdf;

ChromePdfRenderer renderer = new ChromePdfRenderer();
PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>testing</h1>");

// Configure the required parameters
int pageIndex = 0;
var start = new IronSoftware.Drawing.PointF(200,150);
var end = new IronSoftware.Drawing.PointF(1000,150);
int width = 10;
var color = new IronSoftware.Drawing.Color("#000000");

// Draw line on PDF
pdf.DrawLine(pageIndex, start, end, width, color);

pdf.SaveAs("drawLine.pdf");
Imports IronPdf

Private renderer As New ChromePdfRenderer()
Private pdf As PdfDocument = renderer.RenderHtmlAsPdf("<h1>testing</h1>")

' Configure the required parameters
Private pageIndex As Integer = 0
Private start = New IronSoftware.Drawing.PointF(200,150)
Private [end] = New IronSoftware.Drawing.PointF(1000,150)
Private width As Integer = 10
Private color = New IronSoftware.Drawing.Color("#000000")

' Draw line on PDF
pdf.DrawLine(pageIndex, start, [end], width, color)

pdf.SaveAs("drawLine.pdf")
$vbLabelText   $csharpLabel

有關此程式碼片段的更詳細解釋以及探索其附加功能,請參閱我們的綜合操作指南

旋轉文字和頁面

要旋轉 PDF 頁面,我們可以使用SetPageRotation方法來旋轉特定頁面。 在下面的範例中,我們只輪換第 2 頁到第 4 頁,保持第 1 頁不變,以展示其功能。

:path=/static-assets/pdf/content-code-examples/how-to/rotating-text-set-page-rotation.cs
using IronPdf;
using IronPdf.Rendering;
using System.Linq;

// Import PDF
PdfDocument pdf = PdfDocument.FromFile("multi-page.pdf");

// Set rotation for a single page
pdf.SetPageRotation(0, PdfPageRotation.Clockwise90);

// Set rotation for multiple pages
pdf.SetPageRotations(Enumerable.Range(1,3), PdfPageRotation.Clockwise270);

// Set rotation for the entire document
pdf.SetAllPageRotations(PdfPageRotation.Clockwise180);

pdf.SaveAs("rotated.pdf");
Imports IronPdf
Imports IronPdf.Rendering
Imports System.Linq

' Import PDF
Private pdf As PdfDocument = PdfDocument.FromFile("multi-page.pdf")

' Set rotation for a single page
pdf.SetPageRotation(0, PdfPageRotation.Clockwise90)

' Set rotation for multiple pages
pdf.SetPageRotations(Enumerable.Range(1,3), PdfPageRotation.Clockwise270)

' Set rotation for the entire document
pdf.SetAllPageRotations(PdfPageRotation.Clockwise180)

pdf.SaveAs("rotated.pdf")
$vbLabelText   $csharpLabel

有關旋轉角度的可用枚舉列表,請參閱此處

有關此程式碼片段的更詳細解釋以及探索其附加功能,請參閱我們的綜合操作指南

轉換PDF頁面

除了旋轉之外,我們還可以透過提供一系列參數來變換 PDF 頁面。 在下面的範例中,我們選擇 PDF 的第一頁,並使用Transform,將第一頁的內容向右下方移動 50 點,並將其縮放至原始大小的 80%。

:path=/static-assets/pdf/content-code-examples/how-to/transform-pdf-pages-transform-pdf.cs
using IronPdf;

PdfDocument pdf = PdfDocument.FromFile("basic.pdf");

pdf.Pages[0].Transform(50, 50, 0.8, 0.8);

pdf.SaveAs("transformPage.pdf");
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

有關此程式碼片段的更詳細解釋以及探索其附加功能,請參閱我們的綜合操作指南

結論

以上範例表明,IronPDF 在編輯 PDF 時具有開箱即用的關鍵功能。

如果您想提出功能請求或對 IronPDF 或許可有任何一般性問題,請聯絡我們的支援團隊。 我們非常樂意為您提供協助。

常見問題解答

如何用 C# 編輯 PDF 文件?

IronPDF 提供用 C# 編輯 PDF 文件的全面工具。您可以使用 AddPageRemovePage 等方法有效地操作頁面、新增或刪除內容,以及套用各種修改。

使用 C# 在 PDF 上加入水印的步驟是什麼?

要在 C# 中為 PDF 加入水印,請使用 IronPDF 的 ApplyWatermark 方法與 TextStamper 類,讓您可以自訂水印的文字、不透明度和旋轉。

如何使用 C# 壓縮 PDF 檔案?

IronPDF 提供 CompressImages 方法,可縮小 PDF 中內嵌圖片的大小,有效壓縮檔案大小。

是否可以在 C# 中為 PDF 加入頁首和頁尾呢?

是的,使用 IronPDF,您可以使用 HtmlHeaderFooterTextHeaderFooter 類別為 PDF 添加頁首和頁尾,您可以定義 HTML 內容或文字,並調整高度等屬性。

用什麼方法可以將多個 PDF 合併為一個文件?

若要合併多個 PDF,請使用 PdfDocument.FromFile 載入每個文件,然後再使用 Merge 方法將它們合併為單一文件,並儲存為新文件。

如何使用 C# 替換 PDF 中的特定文字?

IronPDF 允許您使用 ReplaceTextOnPage 方法來替換 PDF 中的文字,此方法會搜尋頁面上的特定文字,並以程式化的方式替換。

IronPDF 能否方便 PDF 表單的建立與填寫?

是的,IronPDF 支持以编程方式创建 PDF 表单和填充现有表单字段,从而实现与 PDF 文档的动态交互。

如何使用 IronPDF 在 PDF 中添加注释?

IronPDF 提供了為 PDF 添加註釋的功能。您可以使用註解物件來建立文字註解和其他類型的註解,並將它們放置在所需的頁面上。

如何使用 C# 處理 PDF 中的數位簽章?

IronPDF 支援使用 X509Certificate2 數位憑證在 PDF 文件中加入數位簽章,確保文件的真實性和完整性。

是否可以在 C# 中為 PDF 頁面設定背景?

是的,使用 IronPDF,您可以透過套用圖片或顏色背景來為 PDF 頁面設定背景,以強化文件的設計與呈現。

IronPDF 是否與 .NET 10 相容,它有哪些優點?

是的,IronPDF 與 .NET 10 完全相容,並充分利用其性能和語言增強功能。它可以在桌面、Web、MAUI 和服務的 .NET 10 專案中 「正常運作」,並受益於陣列介面方法去虛擬化和堆疊分配增強等改進。

Curtis Chau
技術作家

Curtis Chau 擁有卡爾頓大學計算機科學學士學位,專注於前端開發,擅長於 Node.js、TypeScript、JavaScript 和 React。Curtis 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。

除了開發之外,Curtis 對物聯網 (IoT) 有著濃厚的興趣,探索將硬體和軟體結合的創新方式。在閒暇時間,他喜愛遊戲並構建 Discord 機器人,結合科技與創意的樂趣。

準備好開始了嗎?
Nuget 下載 16,493,056 | Version: 2025.11 剛發表