如何在 C# | IronPDF 中使用 IronPDF 存取所有 PDF DOM 物件

如何使用 C# 存取所有 PDF DOM 物件進行 PDF編輯

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

若要在 C# 中存取 PDF DOM 物件,請使用 IronPDF 的 ObjectModel 屬性,該屬性可讓您透過程式化方式存取 PDF 文件中的文字、圖片及路徑物件,使您能直接讀取、修改、翻譯、縮放及移除元素。

快速入門:使用 IronPDF 存取與更新 PDF DOM 元素

開始使用 IronPDF 的 DOM 存取功能來操作 PDF 文件。 本指南說明如何存取 PDF DOM、選取頁面以及修改文字物件。 載入您的 PDF,存取所需的頁面,並使用幾行程式碼更新內容。

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

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

    var objs = IronPdf.ChromePdfRenderer.RenderUrlAsPdf("https://example.com").Pages.First().ObjectModel;
  3. 部署到您的生產環境進行測試

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

    arrow pointer

如何存取 PDF 中的 DOM 物件?

可透過 PdfPage 物件存取 ObjectModel。 首先,匯入目標 PDF 檔案並存取其 Pages 屬性。 接著,選取任何頁面即可存取 ObjectModel 屬性。 這可讓您以程式化的方式與 PDF 內容互動,就像使用 HTML DOM 元素一樣。

在處理 PDF DOM 物件時,您會存取 PDF 文件的底層結構。 這包括文字元素、圖片、向量圖形 (paths) 以及構成 PDF 視覺呈現的其他內容。 IronPDF 提供面向物件的 PDF 操作方法,可與 C# 應用程式整合。

: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 除錯器顯示具有 BoundingBox 座標和轉換屬性的 TextObjects 集合

ObjectModel 屬性包含 PathObjectTextObject。 每個物件都包含其頁面索引、邊界框、縮放比例及翻譯的相關資訊。 這些資訊可以修改。 對於 渲染選項,您可以自訂這些物件的顯示方式。 在使用 自訂邊界時,瞭解物件的定位非常重要。

<ImageObject>:

  • Height:圖片高度
  • Width:圖片寬度
  • ExportBytesAsJpg:將圖片匯出為 JPG 位元組陣列的方法

<PathObject>:

  • FillColor:路徑的填充顏色
  • StrokeColor:路徑的筆畫顏色
  • Points:定義路徑的點集合

<TextObject>:

  • Color: 文字的顏色
  • Contents:實際文字內容

每個物件類型都提供針對其內容類型量身打造的方法與屬性。 當您需要抽取文字和圖片或修改特定內容時,這些物件可提供細緻的控制。 在使用 IronPDF 表單,需要以程式化方式操作表單欄位時,這將非常有用。

如何擷取字形資訊和邊界框?

在使用自訂字型指定精確字形時,擷取邊界框和字形資訊至關重要。 當 在現有 PDF 上繪製文字和位圖時,IronPDF 會提供這些資訊,以達到像素完美定位。

PdfPage 物件存取 ObjectModel。 接著存取 TextObjects 集合。 呼叫 GetGlyphInfo 方法以取得字形與邊界框資訊。

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

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

var glyph = pdf.Pages.First().ObjectModel.TextObjects.First().GetGlyphInfo();
Imports IronPdf
Imports System.Linq

Dim pdf As PdfDocument = PdfDocument.FromFile("invoice.pdf")

Dim glyph = pdf.Pages.First().ObjectModel.TextObjects.First().GetGlyphInfo()
$vbLabelText   $csharpLabel
調試器顯示 PDF 字形物件的屬性,包括座標、邊界和文字內容細節

字形資訊包括定位資料、字型度量以及進階 PDF 操作的特定字元細節。 這樣才能建立處理複雜排版和版面需求的 PDF 處理應用程式。 當使用 自訂字型時,此字形層級的存取可確保跨系統的精確呈現。


如何翻譯 PDF 物件?

透過重新定位文字或圖片等元素來調整 PDF 排版。 透過變更物件的 Translate 屬性來移動物件。 此功能是 IronPDF 的 PDF 轉換功能的一部分。

以下範例使用 CSS Flexbox 將 HTML 譯成居中文字。 它存取第一個 TextObject,並透過將新的 PointF 指派給 Translate 屬性來進行翻譯。 這將文字右移 200 點,上移 150 點。如需更多範例,請造訪 翻譯 PDF 物件範例頁

我使用什麼程式碼來翻譯物件?

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

// Setup the Renderer
var renderer = new ChromePdfRenderer();

// We use CSS Flexbox to perfectly center the text vertically and horizontally.
var html = @"
<div style='display: flex; justify-content: center; align-items: center; font-size: 48px;'>
    Centered
</div>";

// Render the HTML to a PDF
PdfDocument pdf = renderer.RenderHtmlAsPdf(html);

// Save the original PDF to see the "before" state
pdf.SaveAs("BeforeTranslate.pdf");

// Access the first text object on the first page
// In this simple HTML, this will be our "Centered" text block.
var textObject = pdf.Pages.First().ObjectModel.TextObjects.First();

// Apply the translation
// This moves the object 200 points to the right and 150 points up from its original position.
textObject.Translate = new PointF(200, 150);

// Save the modified PDF to see the "after" state
pdf.SaveAs("AfterTranslate.pdf");
Imports IronPdf
Imports System.Drawing
Imports System.Linq

' Setup the Renderer
Dim renderer As New ChromePdfRenderer()

' We use CSS Flexbox to perfectly center the text vertically and horizontally.
Dim html As String = "
<div style='display: flex; justify-content: center; align-items: center; font-size: 48px;'>
    Centered
</div>"

' Render the HTML to a PDF
Dim pdf As PdfDocument = renderer.RenderHtmlAsPdf(html)

' Save the original PDF to see the "before" state
pdf.SaveAs("BeforeTranslate.pdf")

' Access the first text object on the first page
' In this simple HTML, this will be our "Centered" text block.
Dim textObject = pdf.Pages.First().ObjectModel.TextObjects.First()

' Apply the translation
' This moves the object 200 points to the right and 150 points up from its original position.
textObject.Translate = New PointF(200, 150)

' Save the modified PDF to see the "after" state
pdf.SaveAs("AfterTranslate.pdf")
$vbLabelText   $csharpLabel

翻譯結果是什麼樣子?

輸出結果顯示"Centered"從原始位置右移 200 點並上移 150 點。

PDF 翻譯前後的比較,顯示保留的文字定位和格式

翻譯作業必須維持物件的原始屬性,例如字型、大小和顏色,同時只改變位置。 這非常適合在不影響視覺外觀的情況下進行版面調整。 在重新定位動態產生的內容時,此功能可與 標頭和頁尾配合使用。


如何縮放 PDF 物件?

使用 Scale 屬性調整 PDF 物件的大小。 該屬性起到乘數作用。 值大於 1 會增加大小,而值介於 0 與 1 之間會減少大小。 縮放對於動態佈局和調整內容以符合頁面尺寸是非常重要的。 請參閱 scale PDF 物件指南,以瞭解更多範例。

本範例渲染包含圖片的 HTML。 它存取第一個 ImageObject,並透過將 Scale 賦予新的 PointF(兩軸皆設為 0.7),將其縮放至 70%。

縮放 PDF 物件的程式碼是什麼?

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

// Setup the Renderer
var renderer = new ChromePdfRenderer();

// The image is placed in a div to give it some space on the page.
string html = @"<img src='https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTi8LuOR6_A98euPLs-JRwoLU7Nc31nVP15rw&s'>";

// Render the HTML to a PDF
PdfDocument pdf = renderer.RenderHtmlAsPdf(html);

// Save the PDF before scaling for comparison
pdf.SaveAs("BeforeScale.pdf");

// Access the first image object on the first page
var image = pdf.Pages.First().ObjectModel.ImageObjects.First();

// We scale the image to 70% of its original size on both the X and Y axes.
image.Scale = new System.Drawing.PointF(0.7f, 0.7f);

// Save the modified PDF to see the result
pdf.SaveAs("AfterScale.pdf");
Imports IronPdf
Imports System.Linq
Imports System.Drawing

' Setup the Renderer
Dim renderer As New ChromePdfRenderer()

' The image is placed in a div to give it some space on the page.
Dim html As String = "<img src='https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTi8LuOR6_A98euPLs-JRwoLU7Nc31nVP15rw&s'>"

' Render the HTML to a PDF
Dim pdf As PdfDocument = renderer.RenderHtmlAsPdf(html)

' Save the PDF before scaling for comparison
pdf.SaveAs("BeforeScale.pdf")

' Access the first image object on the first page
Dim image = pdf.Pages.First().ObjectModel.ImageObjects.First()

' We scale the image to 70% of its original size on both the X and Y axes.
image.Scale = New PointF(0.7F, 0.7F)

' Save the modified PDF to see the result
pdf.SaveAs("AfterScale.pdf")
$vbLabelText   $csharpLabel

對 X 和 Y 軸獨立套用不同的縮放因子,以達到非均勻縮放的效果。 這對於將內容融入特定的維度非常有用。 在使用 自訂紙張尺寸時,縮放有助於確保內容符合頁面邊界。

實際中的擴充是什麼樣子?

輸出結果顯示影像縮放至原始尺寸的 70%。

PDF 縮放示範:Iron 標誌從大尺寸 (左) 縮放至小尺寸 (右),箭頭顯示轉換情況

如何移除 PDF 物件?

透過存取 PDF DOM 集合(例如 ImageObjectsTextObjects)來移除物件。 在集合上呼叫 RemoveAt,並傳入要刪除的物件索引。 這對於編輯內容或簡化文件非常有用。 瞭解更多資訊,請參閱 移除 PDF 物件範例

程式碼載入 BeforeScale.pdf,並移除第一頁的第一張圖片。

我應該使用什麼程式碼來移除物件?

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

// Load the PDF file we created in the Scale example
PdfDocument pdf = PdfDocument.FromFile("BeforeScale.pdf");

// Access DOM Objects
var objects = pdf.Pages.First().ObjectModel;

// Remove first image
objects.ImageObjects.RemoveAt(0);

// Save the modified PDF
pdf.SaveAs("removedFirstImage.pdf");
Imports IronPdf
Imports System.Linq

' Load the PDF file we created in the Scale example
Dim pdf As PdfDocument = PdfDocument.FromFile("BeforeScale.pdf")

' Access DOM Objects
Dim objects = pdf.Pages.First().ObjectModel

' Remove first image
objects.ImageObjects.RemoveAt(0)

' Save the modified PDF
pdf.SaveAs("removedFirstImage.pdf")
$vbLabelText   $csharpLabel

當我移除多個物件時會發生什麼事?

移除後剩餘物件的索引會移位。 移除多個物件時,請以相反順序移除,以維持正確的索引。 當您刪除敏感文件中的文字時,這項技術會有所幫助。

如何結合多個 DOM 作業?

IronPDF 的 DOM 存取功能可實現複雜的文件處理工作流程。 結合複雜轉換的操作:

何時應該使用聯合作業?

// Example of combining multiple DOM operations
using IronPdf;
using System.Linq;

PdfDocument pdf = PdfDocument.FromFile("complex-document.pdf");

// Iterate through all pages
foreach (var page in pdf.Pages)
{
    var objects = page.ObjectModel;

    // Process text objects
    foreach (var textObj in objects.TextObjects)
    {
        // Change color of specific text
        if (textObj.Contents.Contains("Important"))
        {
            textObj.Color = System.Drawing.Color.Red;
        }
    }

    // Scale down all images by 50%
    foreach (var imgObj in objects.ImageObjects)
    {
        imgObj.Scale = new System.Drawing.PointF(0.5f, 0.5f);
    }
}

pdf.SaveAs("processed-document.pdf");
// Example of combining multiple DOM operations
using IronPdf;
using System.Linq;

PdfDocument pdf = PdfDocument.FromFile("complex-document.pdf");

// Iterate through all pages
foreach (var page in pdf.Pages)
{
    var objects = page.ObjectModel;

    // Process text objects
    foreach (var textObj in objects.TextObjects)
    {
        // Change color of specific text
        if (textObj.Contents.Contains("Important"))
        {
            textObj.Color = System.Drawing.Color.Red;
        }
    }

    // Scale down all images by 50%
    foreach (var imgObj in objects.ImageObjects)
    {
        imgObj.Scale = new System.Drawing.PointF(0.5f, 0.5f);
    }
}

pdf.SaveAs("processed-document.pdf");
Imports IronPdf
Imports System.Linq
Imports System.Drawing

Dim pdf As PdfDocument = PdfDocument.FromFile("complex-document.pdf")

' Iterate through all pages
For Each page In pdf.Pages
    Dim objects = page.ObjectModel

    ' Process text objects
    For Each textObj In objects.TextObjects
        ' Change color of specific text
        If textObj.Contents.Contains("Important") Then
            textObj.Color = Color.Red
        End If
    Next

    ' Scale down all images by 50%
    For Each imgObj In objects.ImageObjects
        imgObj.Scale = New PointF(0.5F, 0.5F)
    Next
Next

pdf.SaveAs("processed-document.pdf")
$vbLabelText   $csharpLabel

哪些是合併作業的常見使用案例?

結合 DOM 作業對於下列項目有很好的效果:

1.批次文件處理:處理文件以規範格式或刪除敏感內容
2.動態報表產生:利用即時資料修改範本 PDF,同時控製版面
3.內容遷移:從 PDF 檔案中提取內容並重新組織成新的佈局
4.提昇文件可存取性:透過調整文字大小、對比或間距來增強文件的可存取性。

這些技術可讓功能強大的 PDF 處理應用程式處理複雜的修改。 有關管理文件屬性,請參閱 metadata 管理指南

DOM 存取與其他 PDF 操作方法相比如何?

與傳統方法相比,使用 PDF DOM 工作具有優勢:

// Example: Selective content modification based on criteria
using IronPdf;
using System.Linq;

PdfDocument report = PdfDocument.FromFile("quarterly-report.pdf");

foreach (var page in report.Pages)
{
    var textObjects = page.ObjectModel.TextObjects;

    // Highlight negative values in financial reports
    foreach (var text in textObjects)
    {
        if (text.Contents.StartsWith("-$") || text.Contents.Contains("Loss"))
        {
            text.Color = System.Drawing.Color.Red;
        }
    }
}

report.SaveAs("highlighted-report.pdf");
// Example: Selective content modification based on criteria
using IronPdf;
using System.Linq;

PdfDocument report = PdfDocument.FromFile("quarterly-report.pdf");

foreach (var page in report.Pages)
{
    var textObjects = page.ObjectModel.TextObjects;

    // Highlight negative values in financial reports
    foreach (var text in textObjects)
    {
        if (text.Contents.StartsWith("-$") || text.Contents.Contains("Loss"))
        {
            text.Color = System.Drawing.Color.Red;
        }
    }
}

report.SaveAs("highlighted-report.pdf");
Imports IronPdf
Imports System.Linq

Dim report As PdfDocument = PdfDocument.FromFile("quarterly-report.pdf")

For Each page In report.Pages
    Dim textObjects = page.ObjectModel.TextObjects

    ' Highlight negative values in financial reports
    For Each text In textObjects
        If text.Contents.StartsWith("-$") OrElse text.Contents.Contains("Loss") Then
            text.Color = System.Drawing.Color.Red
        End If
    Next
Next

report.SaveAs("highlighted-report.pdf")
$vbLabelText   $csharpLabel

單靠 HTML 到 PDF 的轉換是無法實現這種粒度控制的,因此 DOM 存取對於複雜的 PDF 處理而言是不可或缺的。

準備好看看您還能做些什麼嗎? 在此查看教學頁面: 編輯 PDFs

常見問題解答

在 PDF 操作中,ObjectModel 屬性是用來做什麼的?

IronPDF 中的 ObjectModel 屬性提供對 PDF 文件中的文字、影像和路徑物件的程式化存取。它允許開發人員直接從 PDF DOM 讀取、修改、翻譯、縮放和移除元素,就像處理 HTML DOM 元素一樣。

如何在 C# 中存取 PDF DOM 物件?

要使用 IronPDF 存取 PDF DOM 物件,首先匯入您的目標 PDF 文件,然後存取其 Pages 屬性。從那裡,選擇任何頁面,並使用 ObjectModel 屬性。例如: var objs = IronPDF.ChromePdfRenderer.RenderUrlAsPdf("https://example.com").Pages.First().ObjectModel;

我可以透過 PDF DOM 存取哪些類型的物件?

IronPDF 的 ObjectModel 包含三種主要物件類型:ImageObject(具有高度、寬度和 ExportBytesAsJpg 等屬性)、PathObject(具有 FillColor、StrokeColor 和 Points 等屬性)和 TextObject(具有 Color 和 Contents 等屬性)。每種物件都提供針對其特定內容類型的方法。

我可以程式化地修改 PDF 文件內的文字內容嗎?

是的,IronPDF 允許您透過 TextObject 的 Contents 屬性修改文字內容。您只需要幾行程式碼就可以透過 ObjectModel 存取文字物件、更新其內容,並儲存修改後的 PDF 文件。

如何從 PDF 文件匯出影像?

IronPDF 的 ImageObject 提供 ExportBytesAsJpg 方法,可以將圖像匯出為 JPG 位元組陣列。透過 ObjectModel 屬性存取影像,並使用此方法以程式化的方式擷取影像資料。

每個 DOM 物件的位置有哪些資訊?

IronPDF ObjectModel 中的每個物件都包含其頁面索引、邊界框座標、縮放比例和平移等資訊。此定位資料可被讀取與修改,以重新定位或轉換 PDF 中的元素。

Curtis Chau
技術作家

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

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

準備好開始了嗎?
Nuget 下載 18,560,885 | 版本: 2026.4 剛剛發布
Still Scrolling Icon

還在捲動嗎?

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