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

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

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. using 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 提供一種可與 C# 應用程式整合的物件導向 PDF 處理方法。

: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。 每個物件皆包含其頁面索引、邊界框、ScaleTranslation 的相關資訊。 此資訊可進行修改。 關於渲染選項,您可以自訂這些物件的顯示方式。 在處理自訂邊距時,理解物件定位至關重要。

<ImageObject>:

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

<PathObject>:

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

<TextObject>:

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

每種物件類型皆提供針對其內容類型量身打造的方法與屬性。 當您需要擷取文字與圖片,或修改特定內容時,這些物件能提供細緻的控制能力。 這在處理 PDF 表單時特別有用,當您需要透過程式碼操作表單欄位時。

如何取得字形資訊與邊界框?

在使用自訂字型指定精確字形時,取得邊界框與字形資訊至關重要。 IronPDF 提供此資訊,以便在現有 PDF 上繪製文字和位圖時實現像素級精準定位。

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

翻譯結果應呈現何種樣貌?

輸出結果顯示"居中"文字相較原始位置向右 Shift 了 200 點,並向上移動了 150 點。

PDF 翻譯前後對照圖,顯示原始文字位置與格式均已完整保留

翻譯操作會保留物件的原始屬性(如字型、大小和顏色),僅調整其位置。 此格式非常適合進行版面調整,且不會影響視覺呈現。 此功能在重新定位動態生成的內容時,會與頁首和頁尾協同運作。


如何調整 PDF 物件的大小?

使用 Scale 屬性調整 PDF 物件的大小。 此屬性會產生倍增效果。 數值大於 1 會增加大小,而介於 0 到 1 之間的數值則會減少大小。 縮放功能對於動態版面配置及調整內容以適應頁面尺寸至關重要。 請參閱 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 處理應用程式,以處理複雜的修改作業。 有關文件屬性的管理,請參閱元資料管理指南

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 無法實現這種細緻的控制,因此對於複雜的 PDF 處理而言,DOM 存取至關重要。

準備好探索更多可能性了嗎? 請點此查看教學頁面:編輯 PDF

常見問題

在 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(具有 Height、Width 和 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 擁有卡爾頓大學(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。