C#에서 모든 PDF DOM 객체에 접근하는 방법
C#에서 PDF DOM 객체에 접근하려면 IronPDF의 ObjectModel 속성을 사용하세요. 이 속성을 통해 PDF 문서의 텍스트, 이미지, 경로 객체에 코드로 접근하여 요소를 직접 읽고 수정하거나, 이동하거나, 크기를 조정하거나, 제거할 수 있습니다.
IronPDF의 DOM 접근 기능을 사용하여 PDF 문서를 조작해 보세요. 이 가이드에서는 PDF DOM에 접근하고, 페이지를 선택하고, 텍스트 객체를 수정하는 방법을 보여줍니다. PDF 파일을 불러와 원하는 페이지에 접근한 후, 몇 줄의 코드로 콘텐츠를 업데이트하세요.
-
1IronPDF를 NuGet Package Manager로 설치하십시오
-
2다음 코드 조각을 복사하여 실행하세요.
using System.Linq; var objs = IronPdf.PdfDocument.FromFile("input.pdf").Pages.First().ObjectModel;Imports System.Linq Dim objs = IronPdf.PdfDocument.FromFile("input.pdf").Pages.First().ObjectModelImports System.Linq Dim objs = IronPdf.PdfDocument.FromFile("input.pdf").Pages.First().ObjectModel -
3실제 운영 환경에서 테스트할 수 있도록 배포하세요.
오늘 프로젝트에서 IronPDF 사용을 시작해보세요 무료 체험
최소 워크플로우(5단계)
- PDF DOM 객체에 접근하려면 C# 라이브러리를 다운로드하세요.
- 대상 PDF 문서를 가져오거나 렌더링하세요.
- PDF의
Pages컬렉션에서 원하는 페이지를 선택하세요. - ObjectModel 속성을 사용하여 DOM 객체를 확인하고 조작하세요.
- 수정된 PDF 문서를 저장하거나 내보내세요.
PDF 파일에서 DOM 객체에 접근하는 방법은 무엇인가요?
PdfPage 객체에서 ObjectModel에 접근할 수 있습니다. 먼저 대상 PDF를 가져온 뒤 Pages 속성에서 원하는 페이지를 선택하고 해당 페이지의 ObjectModel 속성에 접근하세요. HTML DOM 요소를 다루듯이 코드로 PDF 콘텐츠를 조작할 수 있습니다.
PDF DOM 객체를 다룰 때는 PDF 문서의 기본 구조에 접근할 수 있습니다. 이것은 텍스트 요소, 이미지, 벡터 그래픽(paths) 및 PDF의 시각적 표현을 구성하는 기타 콘텐츠를 포함합니다. IronPDF는 C# 애플리케이션과 통합되는 객체 지향적인 PDF 조작 방식을 제공합니다.
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;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().ObjectModelImports 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
ObjectModel 속성에는 ImageObject, PathObject, TextObject가 포함됩니다. 각 객체에는 페이지 인덱스, 경계 상자, Scale, Translate 정보가 있습니다. 이 정보는 수정할 수 있지만, 적용된 스탬프처럼 Form XObject 내부에 있는 객체의 변경 사항은 오류 없이 무시됩니다. 렌더링 옵션으로 이러한 객체의 표시 방식을 설정할 수 있습니다. 사용자 지정 여백을 설정할 때는 객체의 위치를 파악하는 것이 중요합니다.
<ImageObject>:
Height: 이미지 높이Width: 이미지 너비ExportBytesAsJpg: 이미지를 JPG 바이트 배열로 내보내는 메서드
<PathObject>:
FillColor: 경로의 채움 색상StrokeColor: 경로의 스트로크 색상Points: 경로를 정의하는 점의 컬렉션StrokeWidth: PDF 사용자 공간 단위의 선 두께LineCap: 끝점 스타일(Butt,Round, 또는ProjectingSquare)LineJoin: 모서리 스타일(Miter,Round, 또는Bevel)DashPattern: 번갈아 나타나는 대시와 간격의 길이. 실선인 경우 빈 값DashPhase: 대시 패턴 내의 오프셋OcgId: 경로가 속한 레이어의 ID, 또는 모든 레이어 외부에 있을 때는-1GetLayer(): 일치하는PdfLayer을 반환하거나null을 반환합니다.
<TextObject>:
Color: 텍스트의 색상Contents: 실제Text콘텐츠EffectiveFontSize:FontSize와 달리 텍스트 행렬로 크기를 조정한 후 페이지에 실제로 그려지는 글꼴 크기SpanOrigin: 경계 상자와 무관한 텍스트 기준선의 원점OcgId: 텍스트가 속한 레이어의 ID, 또는 모든 레이어 외부에 있을 때는-1GetLayer(): 일치하는PdfLayer을 반환하거나null을 반환합니다.
각 객체 유형은 콘텐츠에 맞는 메서드와 속성을 제공합니다. 텍스트와 이미지를 추출하거나 특정 콘텐츠를 수정할 때 객체 단위로 세밀하게 제어할 수 있습니다. 코드로 PDF 양식의 필드를 조작할 때도 유용합니다.
글리프 정보와 경계 상자를 가져오는 방법
사용자 지정 글꼴로 특정 글리프를 지정하려면 경계 상자와 글리프 정보가 필요합니다. IronPDF는 기존 PDF에 텍스트와 비트맵을 그릴 때 픽셀 단위로 정확하게 배치할 수 있도록 이 정보를 제공합니다.
PdfPage 객체의 ObjectModel을 통해 TextObjects 컬렉션에 접근하세요. GetGlyphInfo 메서드를 호출하면 글리프 정보와 경계 상자를 가져올 수 있습니다.
using IronPdf;
using System.Linq;
PdfDocument pdf = PdfDocument.FromFile("invoice.pdf");
var glyph = pdf.Pages.First().ObjectModel.TextObjects.First().GetGlyphInfo();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()Imports IronPdf
Imports System.Linq
Dim pdf As PdfDocument = PdfDocument.FromFile("invoice.pdf")
Dim glyph = pdf.Pages.First().ObjectModel.TextObjects.First().GetGlyphInfo()
글리프 정보에는 고급 PDF 조작에 필요한 위치 데이터, 글꼴 메트릭, 문자별 세부 정보가 포함됩니다. 이러한 정보로 복잡한 타이포그래피와 레이아웃 요구 사항을 처리하는 PDF 애플리케이션을 만들 수 있습니다. 사용자 지정 글꼴을 사용할 때 글리프 단위로 접근하면 여러 시스템에서 정확하게 렌더링할 수 있습니다.
PDF 레이어(선택적 콘텐츠 그룹)를 사용하려면 어떻게 해야 하나요?
레이어가 있는 PDF는 도면 위에 트레이싱지를 겹쳐 놓듯 이름이 붙은 레이어에 콘텐츠를 쌓습니다. Acrobat의 레이어 패널에 표시되는 이 레이어를 선택적 콘텐츠 그룹(OCG)이라고 합니다. PdfDocument.Layers 컬렉션으로 모든 레이어에 접근할 수 있습니다. 레이어를 열거하거나, Id 또는 Name으로 특정 레이어를 찾거나, ChildrenOf로 부모·자식 트리를 탐색하거나, 단일 레이어의 콘텐츠를 읽을 수 있습니다. 레이어 조회는 읽기 전용이며 이름, 순서, 표시 상태를 변경하지 않습니다. 각 PdfLayer는 Id, Name, IsVisible, DefaultVisible, ParentId를 제공합니다.
using IronPdf;
using IronSoftware;
using System;
// Load a layered PDF, such as a CAD plan, engineering drawing, or map export
using PdfDocument pdf = new PdfDocument("blueprint.pdf");
// Enumerate every Optional Content Group (OCG) layer in the document
Console.WriteLine($"Document has {pdf.Layers.Count} layers");
foreach (PdfLayer layer in pdf.Layers)
{
Console.WriteLine($" {layer.Id}: \"{layer.Name}\" visible={layer.IsVisible} parent={layer.ParentId}");
}
// Look a layer up by name (case-sensitive) and extract just its text
PdfLayer titleBlock = pdf.Layers.FindByName("Title Block");
if (titleBlock != null)
{
string headerText = pdf.ExtractTextFromLayer(titleBlock.Id);
Console.WriteLine(headerText);
}using IronPdf;
using IronSoftware;
using System;
// Load a layered PDF, such as a CAD plan, engineering drawing, or map export
using PdfDocument pdf = new PdfDocument("blueprint.pdf");
// Enumerate every Optional Content Group (OCG) layer in the document
Console.WriteLine($"Document has {pdf.Layers.Count} layers");
foreach (PdfLayer layer in pdf.Layers)
{
Console.WriteLine($" {layer.Id}: \"{layer.Name}\" visible={layer.IsVisible} parent={layer.ParentId}");
}
// Look a layer up by name (case-sensitive) and extract just its text
PdfLayer titleBlock = pdf.Layers.FindByName("Title Block");
if (titleBlock != null)
{
string headerText = pdf.ExtractTextFromLayer(titleBlock.Id);
Console.WriteLine(headerText);
}Imports IronPdf
Imports IronSoftware
Imports System
' Load a layered PDF, such as a CAD plan, engineering drawing, or map export
Using pdf As New PdfDocument("blueprint.pdf")
' Enumerate every Optional Content Group (OCG) layer in the document
Console.WriteLine($"Document has {pdf.Layers.Count} layers")
For Each layer As PdfLayer In pdf.Layers
Console.WriteLine($" {layer.Id}: ""{layer.Name}"" visible={layer.IsVisible} parent={layer.ParentId}")
Next
' Look a layer up by name (case-sensitive) and extract just its text
Dim titleBlock As PdfLayer = pdf.Layers.FindByName("Title Block")
If titleBlock IsNot Nothing Then
Dim headerText As String = pdf.ExtractTextFromLayer(titleBlock.Id)
Console.WriteLine(headerText)
End If
End UsingImports IronPdf
Imports IronSoftware
Imports System
' Load a layered PDF, such as a CAD plan, engineering drawing, or map export
Using pdf As New PdfDocument("blueprint.pdf")
' Enumerate every Optional Content Group (OCG) layer in the document
Console.WriteLine($"Document has {pdf.Layers.Count} layers")
For Each layer As PdfLayer In pdf.Layers
Console.WriteLine($" {layer.Id}: ""{layer.Name}"" visible={layer.IsVisible} parent={layer.ParentId}")
Next
' Look a layer up by name (case-sensitive) and extract just its text
Dim titleBlock As PdfLayer = pdf.Layers.FindByName("Title Block")
If titleBlock IsNot Nothing Then
Dim headerText As String = pdf.ExtractTextFromLayer(titleBlock.Id)
Console.WriteLine(headerText)
End If
End UsingExtractTextFromLayer 외에도, ExtractTextFromLayers로 여러 레이어를 한 번에 가져오거나 GetTextObjectsByLayer 및 GetPathObjectsByLayer로 객체 자체에 접근할 수 있습니다. 더 넓은 추출 작업 흐름의 일부로서 레이어별 텍스트를 위해 텍스트 및 이미지 추출 가이드를 참조하세요.
FindByName("title block")은(는) "Title Block"과 일치하지 않습니다. 레이어가 없는 PDF는 null 대신 빈 컬렉션을 반환하므로 null 검사를 하지 않고도 pdf.Layers을(를) 열거할 수 있습니다.선 스타일로 CAD 도면 요소를 구분하는 방법
일부 도면에는 레이어 정보가 전혀 없습니다. 측량 및 CAD 도구에서 내보낸 PDF에는 OCG가 없는 경우가 많으므로 선의 모양으로 도면 요소를 구분해야 합니다. 각 PathObject는 그래픽 상태(StrokeWidth, LineCap, LineJoin, DashPattern, DashPhase)를 제공하므로 파선 경계와 실선 윤곽선, 굵은 선으로 표시된 도로와 가는 선으로 표시된 도로를 구분할 수 있습니다.
using IronPdf;
using IronSoftware;
using System;
using System.Linq;
// PDFs from surveying and CAD tools often have no layer information.
// Distinguish features by each path's graphics-state attributes instead.
using PdfDocument pdf = new PdfDocument("survey-drawing.pdf");
var paths = pdf.Pages.First().ObjectModel.PathObjects;
foreach (PathObject path in paths)
{
bool isDashed = path.DashPattern.Count > 0;
Console.WriteLine(
$"width={path.StrokeWidth} cap={path.LineCap} join={path.LineJoin} " +
$"dashed={isDashed} color={path.StrokeColor}");
}using IronPdf;
using IronSoftware;
using System;
using System.Linq;
// PDFs from surveying and CAD tools often have no layer information.
// Distinguish features by each path's graphics-state attributes instead.
using PdfDocument pdf = new PdfDocument("survey-drawing.pdf");
var paths = pdf.Pages.First().ObjectModel.PathObjects;
foreach (PathObject path in paths)
{
bool isDashed = path.DashPattern.Count > 0;
Console.WriteLine(
$"width={path.StrokeWidth} cap={path.LineCap} join={path.LineJoin} " +
$"dashed={isDashed} color={path.StrokeColor}");
}Imports IronPdf
Imports IronSoftware
Imports System
Imports System.Linq
' PDFs from surveying and CAD tools often have no layer information.
' Distinguish features by each path's graphics-state attributes instead.
Dim pdf As New PdfDocument("survey-drawing.pdf")
Dim paths = pdf.Pages.First().ObjectModel.PathObjects
For Each path As PathObject In paths
Dim isDashed As Boolean = path.DashPattern.Count > 0
Console.WriteLine($"width={path.StrokeWidth} cap={path.LineCap} join={path.LineJoin} dashed={isDashed} color={path.StrokeColor}")
NextImports IronPdf
Imports IronSoftware
Imports System
Imports System.Linq
' PDFs from surveying and CAD tools often have no layer information.
' Distinguish features by each path's graphics-state attributes instead.
Dim pdf As New PdfDocument("survey-drawing.pdf")
Dim paths = pdf.Pages.First().ObjectModel.PathObjects
For Each path As PathObject In paths
Dim isDashed As Boolean = path.DashPattern.Count > 0
Console.WriteLine($"width={path.StrokeWidth} cap={path.LineCap} join={path.LineJoin} dashed={isDashed} color={path.StrokeColor}")
Next예제에서는 각 경로의 선 두께, 끝 모양, 연결 모양, 파선 여부, 색상을 콘솔에 출력합니다. PDF에 레이어가 없어도 파선 경계와 실선 윤곽선을 구분할 수 있습니다.
PDF 객체를 이동하는 방법
텍스트나 이미지 등의 요소를 재배치하여 PDF 레이아웃을 조정하세요. 객체의 Translate 속성을 변경하여 이동합니다. 이 기능은 IronPDF의 PDF 변환 기능의 일부입니다.
아래 예제에서는 CSS Flexbox로 텍스트를 가운데 정렬하는 HTML을 렌더링합니다. 첫 번째 TextObject에 접근한 뒤 Translate 속성에 새 PointF를 할당합니다. 그러면 텍스트가 오른쪽으로 200포인트, 위로 150포인트 이동합니다. 자세한 내용은 PDF 객체 이동 예제를 참조하세요.
객체 이동 코드
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");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")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")출력
출력 결과는 "Centered"가 원래 위치에서 오른쪽으로 200포인트, 위로 150포인트 이동했음을 보여줍니다.

이동 작업은 글꼴, 크기, 색상과 같은 객체의 원래 속성을 유지하면서 위치만 변경합니다. 이는 시각적 외관에 영향을 주지 않고 레이아웃을 조정하는 데 이상적입니다. 이 기능은 동적으로 생성된 콘텐츠를 재배치할 때 헤더 및 푸터와 함께 작동합니다.
PDF 객체의 크기를 어떻게 확대/축소하나요?
Scale 속성으로 PDF 객체의 크기를 조정합니다. 이 속성은 배율을 지정합니다. 값이 1보다 크면 객체가 커지고, 0과 1 사이이면 작아집니다. 동적 레이아웃을 구현하거나 페이지 크기에 콘텐츠를 맞추려면 크기 조정이 필요합니다. 자세한 내용은 PDF 객체 크기 조정 가이드를 참조하세요.
이 예제에서는 이미지가 포함된 HTML을 렌더링합니다. 첫 번째 ImageObject에 접근한 뒤 두 축의 값이 모두 0.7인 새 PointF를 Scale에 할당하여 이미지를 원래 크기의 70%로 줄입니다.
PDF 객체 크기 조정 코드는 무엇인가요?
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");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")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")가로와 세로의 크기를 서로 다른 비율로 조정하려면 X축과 Y축에 각각 다른 배율을 적용하세요. 콘텐츠를 지정된 크기에 맞출 때 유용합니다. 사용자 지정 용지 크기를 사용할 때도 크기를 조정하면 콘텐츠를 페이지 영역 안에 배치할 수 있습니다.
출력
출력 결과는 원본 크기의 70%로 축소된 이미지를 보여줍니다.

PDF 객체를 제거하는 방법
객체를 제거하려면 ImageObjects 또는 TextObjects와 같은 PDF DOM 컬렉션에 접근하세요. 컬렉션의 RemoveAt을 호출할 때 삭제할 객체의 인덱스를 전달하세요. 이 기능은 민감한 콘텐츠를 가리거나 문서를 간소화할 때 유용합니다. 자세한 내용은 PDF 객체 제거 예제를 참조하세요.
Form XObject 내부의 객체: RemoveAt을 호출하면 컬렉션에서 객체가 사라지지만 PDF에는 그대로 남으며 오류도 발생하지 않습니다. 컬렉션의 상태를 판단하기 전에 페이지를 다시 읽으세요.
이 코드는 BeforeScale.pdf 파일을 불러와 첫 페이지의 첫 번째 이미지를 제거합니다.
객체를 제거하려면 어떤 코드를 사용해야 할까요?
입력
제품 이미지를 포함한 PDF입니다.
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");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")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")출력
첫 번째 이미지 객체가 페이지에서 제거되었고, 나머지 콘텐츠는 그대로 남아 있습니다.
여러 객체를 제거할 때 인덱스가 바뀌는 방식
제거 후 남아 있는 객체의 인덱스가 변경됩니다. 여러 객체를 삭제할 때는 인덱스를 올바르게 유지하기 위해 역순으로 삭제하십시오. 이 기술은 민감한 문서에서 텍스트를 삭제할 때 유용합니다.
여러 DOM 작업을 어떻게 결합할 수 있나요?
IronPDF의 DOM 접근 기능으로 복잡한 문서 처리 워크플로를 구현할 수 있습니다. 복잡한 변환이 필요한 경우 여러 작업을 조합하세요.
여러 DOM 작업을 조합하는 경우
입력
원본 PDF에는 "Important"로 표시된 텍스트와 이미지가 포함되어 있습니다.
using IronPdf;
using System.Linq;
// Example of combining multiple DOM operations
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.FillColor = IronSoftware.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");using IronPdf;
using System.Linq;
// Example of combining multiple DOM operations
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.FillColor = IronSoftware.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
' Example of combining multiple DOM operations
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.FillColor = IronSoftware.Drawing.Color.Red
End If
Next
' Scale down all images by 50%
For Each imgObj In objects.ImageObjects
imgObj.Scale = New System.Drawing.PointF(0.5F, 0.5F)
Next
Next
pdf.SaveAs("processed-document.pdf")Imports IronPdf
Imports System.Linq
' Example of combining multiple DOM operations
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.FillColor = IronSoftware.Drawing.Color.Red
End If
Next
' Scale down all images by 50%
For Each imgObj In objects.ImageObjects
imgObj.Scale = New System.Drawing.PointF(0.5F, 0.5F)
Next
Next
pdf.SaveAs("processed-document.pdf")출력
"Important" 텍스트가 빨간색으로 표시되고 이미지 크기가 원래 크기의 50%로 조정됩니다.
통합 작업의 일반적인 사용 사례는 무엇입니까?
결합된 DOM 작업은 다음과 같은 경우에 효과적입니다.
- 문서 일괄 처리: 문서의 형식화 표준화 또는 민감한 내용 제거
- 동적 보고서 생성: 실시간 데이터를 사용해 템플릿 PDF 수정, 레이아웃 제어
- 콘텐츠 마이그레이션: PDF에서 콘텐츠를 추출하여 새 레이아웃으로 재구성
- 접근성 개선: 문서의 텍스트 크기, 대비, 또는 간격 수정하여 향상
이러한 기술 덕분에 복잡한 수정 사항을 처리할 수 있는 강력한 PDF 처리 애플리케이션이 가능해집니다. 문서 속성 관리에 대해서는 메타데이터 관리 가이드를 참조하십시오.
DOM 접근 방식은 다른 PDF 조작 방식과 어떻게 다른가요?
PDF DOM을 사용하면 기존 방식보다 여러 가지 이점이 있습니다.
입력
소스 분기 보고서에는 손실로 표시된 두 수치가 나열되어 있습니다.
using IronPdf;
using System.Linq;
// Example: Selective content modification based on criteria
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.FillColor = IronSoftware.Drawing.Color.Red;
}
}
}
report.SaveAs("highlighted-report.pdf");using IronPdf;
using System.Linq;
// Example: Selective content modification based on criteria
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.FillColor = IronSoftware.Drawing.Color.Red;
}
}
}
report.SaveAs("highlighted-report.pdf");Imports IronPdf
Imports System.Linq
' 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.FillColor = IronSoftware.Drawing.Color.Red
End If
Next
Next
report.SaveAs("highlighted-report.pdf")Imports IronPdf
Imports System.Linq
' 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.FillColor = IronSoftware.Drawing.Color.Red
End If
Next
Next
report.SaveAs("highlighted-report.pdf")출력
-$로 시작하거나 "Loss"가 포함된 값은 모두 빨간색으로 표시됩니다.
HTML에서 PDF 변환만으로는 이러한 세밀한 제어가 불가능하므로 복잡한 PDF 처리를 위해 DOM 액세스가 필수적입니다.
다른 편집 기능은 PDF 편집 튜토리얼을 참조하세요.
자주 묻는 질문
C#에서 PDF DOM 객체에 어떻게 접근할 수 있나요?
IronPDF를 사용하여 C#에서 PDF DOM 객체에 접근하려면 ObjectModel 속성을 활용하세요. 이를 통해 프로그래밍 방식으로 PDF 문서 내의 텍스트, 이미지 및 경로 객체를 읽고, 수정하고, 조작할 수 있습니다.
IronPDF의 `ObjectModel` 속성은 무엇인가요?
IronPDF의 ObjectModel 속성은 PDF DOM에 접근할 수 있게 하며, 지정된 PDF 페이지의 텍스트 객체, 이미지 객체, 경로 객체 등의 요소와 상호작용할 수 있습니다.
IronPDF를 사용하여 PDF 텍스트 객체를 어떻게 수정하나요?
IronPDF에서 PDF 텍스트 객체를 수정하려면 ObjectModel 및 TextObjects 컬렉션을 통해 접근하여 제공된 메소드를 사용해 색상이나 콘텐츠 같은 속성을 변경할 수 있습니다.
IronPDF를 사용하여 PDF에서 글리프 및 바운딩 박스 정보를 추출할 수 있나요?
네, IronPDF는 TextObjects에 접근하고 GetGlyphInfo 메소드를 사용하여 글리프 및 경계 상자 정보를 검색할 수 있어, 정확한 텍스트 위치 지정에 필수적입니다.
IronPDF를 사용하여 PDF의 레이어를 작업할 수 있나요?
IronPDF는 PDF 내의 선택적 콘텐츠 그룹(OCG) 또는 레이어를 다루는 기능을 제공하여 특정 레이어에 범위를 둔 내용 추출과 열거를 할 수 있습니다.
IronPDF를 사용하여 PDF에서 객체를 어떻게 제거하나요?
PDF에서 이미지나 텍스트 같은 객체를 제거하려면 ObjectModel 내의 해당 컬렉션에 접근하고 RemoveAt 함수를 사용하여 인덱스로 객체를 삭제할 수 있습니다.
IronPDF를 사용하여 PDF 객체를 스케일링하는 방법은 무엇인가요?
IronPDF의 ObjectModel의 Scale 속성을 사용하여 PDF 객체를 스케일링할 수 있으며, 스케일 팩터를 지정하여 이미지나 텍스트 같은 요소의 크기를 조정할 수 있습니다.
IronPDF에서 PDF 객체를 어떻게 변환할 수 있나요?
IronPDF에서 객체의 Translate 속성을 조정하여 PDF 객체를 변환할 수 있습니다. 이 재배치는 객체의 시각적 스타일을 변경하지 않고 레이아웃 조정을 가능하게 합니다.
IronPDF를 사용하여 레이어 없이 PDF에서 CAD 기능을 어떻게 구별하나요?
IronPDF는 StrokeWidth, LineCap, DashPattern 같은 PathObject 속성을 분석하여 레이어 없이 CAD 기능을 구별할 수 있습니다.
IronPDF를 사용한 결합된 PDF DOM 작업의 일반적인 사용 사례는 무엇인가요?
결합된 PDF DOM 작업은 대량 문서 처리, 동적 보고서 생성, 콘텐츠 마이그레이션, 문서 접근성 개선에 유용하며 IronPDF를 사용하여 복잡한 수정을 가능하게 합니다.
커티스 차우는 칼턴 대학교에서 컴퓨터 과학 학사 학위를 취득했으며, Node.js, TypeScript, JavaScript, React를 전문으로 하는 프론트엔드 개발자입니다. 직관적이고 미적으로 뛰어난 사용자 인터페이스를 만드는 데 열정을 가진 그는 최신 프레임워크를 활용하고, 잘 구성되고 시각적으로 매력적인 매뉴얼을 제작하는 것을 즐깁니다.