如何在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. 使用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 物件?

ObjectModelPdfPage 物件取得。 首先,匯入目標 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 除錯器顯示帶有邊界框座標及轉換屬性的 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,並給 Translate 屬性分配一個新的 PointF 來翻譯它。 這會將文字向右移動 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 物件?

using Scale 屬性調整 PDF 物件大小。 該屬性充當乘數。 大於 1 的值會增加大小,而在 0 到 1 之間的值則會減少大小。 縮放對於動態佈局和調整內容以適合頁面尺寸至關重要。 欲取得更多範例,請參閱縮放 PDF 物件指南

範例中渲染包含圖像的 HTML。 它存取第一個 ImageObject,並通過為 Scale 指定一個新的 PointF,將其縮放到 70%,在兩個軸上使用 0.7。

縮放 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 從大尺寸(左)縮小到小尺寸(右),箭頭顯示轉換

Icon Quote related to 實踐中縮放看起來如何?

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

Milan Jovanovic related to 實踐中縮放看起來如何?

Milan Jovanovic

Microsoft MVP

查看案例研究
Icon Quote related to 實踐中縮放看起來如何?

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

Brent Matzelle related to 實踐中縮放看起來如何?

Brent Matzelle

首席技術官,OPYN

查看案例研究
Icon Quote related to 實踐中縮放看起來如何?

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

David Jones related to 實踐中縮放看起來如何?

David Jones

首席軟體工程師,Agorus Build

查看案例研究

如何移除 PDF 物件?

透過存取如 ImageObjectsTextObjects 的 PDF DOM 集合來移除物件。 在集合上呼叫 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 存取功能使得復雜文件處理工作流程成為可能。 結合操作以實現復雜轉換:

什麼時候應該使用結合操作?

:path=/static-assets/pdf/content-code-examples/how-to/access-pdf-dom-object-7.cs
// 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 比傳統方法具有優勢:

:path=/static-assets/pdf/content-code-examples/how-to/access-pdf-dom-object-8.cs
// 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
Imports System.Drawing

' Example: Selective content modification based on criteria
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 = Color.Red
        End If
    Next
Next

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

這種細粒度的控制是僅用HTML 轉 PDF 轉換無法實現的,使 DOM 存取成為複雜 PDF 處理的必要條件。

準備好看看您還能做什麼嗎? 請在此處查看教程頁面:編輯 PDF

常見問題

ObjectModel屬性在PDF操作中有什麼用途?

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

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

準備開始了嗎?
Nuget 下載 19,936,792 | 版本: 2026.7 剛剛發布
Still Scrolling Icon

還在捲動嗎?

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