C#에서 iTextSharp와 IronPDF를 사용하여 PDF에 헤더 및 푸터 추가하기
Full Comparison
Looking for a detailed feature-by-feature breakdown? See how IronPDF stacks up against Itext on pricing, HTML support, and licensing.
C#에서 PDF 문서에 헤더 및 풋터 추가하기
PDF 문서에 헤더와 풋터를 추가하는 것은 전문적인 보고서, 청구서 및 비즈니스 문서를 작성하는데 필수적입니다. iTextSharp 솔루션을 검색하는 개발자는 PdfPageEventHelper와 OnEndPage 메서드를 사용하여 동일한 결과를 달성하기 위해 현대적인 .NET 라이브러리가 훨씬 더 간단한 접근 방식을 제공한다는 것을 알게 될 것입니다.
이 가이드는 전통적인 iText 7 접근 방식과 IronPDF의 간결한 API를 비교하여 C#에서 PDF 파일에 헤더와 풋터를 추가하는 방법을 보여줍니다. 마지막에는 새로운 Document를 만드는 것부터 최종 PDF 파일을 생성하는 것까지 두 구현 방식을 이해하게 되며, 프로젝트 요구사항에 가장 적합한 접근 방식을 선택할 수 있습니다.

전문 문서에서 PDF 헤더와 풋터가 중요한 이유는?
헤더와 풋터는 전문 PDF 문서에서 중요한 기능을 제공합니다. 이미지 로고를 통한 일관된 브랜딩, 페이지 번호를 통한 페이지 탐색, 날짜 및 문서 제목과 같은 중요한 메타데이터 표시, 타임스탬프 및 버전 정보를 통한 문서 신뢰성 구축을 제공합니다.
Enterprise 환경에서 헤더와 풋터는 종종 법적 의미를 가집니다. 금융 보고서는 감사 추적의 타임스탬프가 필요합니다. 계약서는 페이지 번호를 사용하여 완전성을 보장해야 합니다. 내부 문서는 페이지마다 기밀 유지 통지가 필요할 수 있습니다. 이 요구사항을 프로그래밍 방식으로 충족하려면 PDF 라이브러리가 페이지 수준의 콘텐츠 삽입을 신뢰성 있게 처리할 수 있어야 합니다.
프로그램적으로 헤더와 풋터를 추가해야 하는 주요 이유는 다음과 같습니다:
- 감사 준수 -- 모든 페이지의 타임스탬프 및 버전 번호가 규제 요구사항을 충족
- 브랜드 일관성 -- 생성된 모든 문서에 일관되게 적용되는 회사 로고 및 스타일
- 탐색 -- 페이지 번호 및 섹션 제목은 독자가 정보를 빠르게 찾을 수 있도록 돕습니다
- 정통성 -- 저자 이름, 생성 날짜, 문서 ID는 문서의 무결성에 대한 논쟁을 방지합니다

C#에서 텍스트 헤더 및 풋터를 어떻게 추가합니까?
IronPDF는 .NET 애플리케이션에서 PDF 문서에 헤더와 풋터를 추가하는 가장 직접적인 방법을 제공합니다. ChromePdfRenderer 클래스와 TextHeaderFooter 또는 HtmlHeaderFooter을 결합하여 최소한의 코드로 헤더와 푸터를 생성할 수 있으며, 별도의 셀을 생성하거나 contentbyte 개체를 수동으로 관리할 필요가 없습니다.
코드를 작성하기 전 NuGet을 사용하여 프로젝트에 IronPDF를 추가하십시오:
Install-Package IronPdf
dotnet add package IronPdf
Install-Package IronPdf
dotnet add package IronPdf
이 라이브러리는 외부 의존성이 필요하지 않으며 설치 직후 바로 작동합니다. .NET 5, 6, 7, 8 및 10을 대상으로 하며, 플랫폼별 설정 없이 Windows, Linux 및 macOS에서 실행됩니다.
옛날 iTextSharp 패턴에서는 개발자가 private static void AddContent()와 같은 도우미 메서드를 생성하여 수동으로 헤더와 푸터 논리를 주입했습니다. IronPDF는 이러한 기본 코드를 완전히 제거합니다.
다음은 PDF 파일에 텍스트 헤더와 푸터를 추가하는 전체 예제입니다:
using IronPdf;
// Initialize the PDF renderer
var renderer = new ChromePdfRenderer();
// Configure the text header
renderer.RenderingOptions.TextHeader = new TextHeaderFooter
{
CenterText = "Quarterly Sales Report",
DrawDividerLine = true,
FontSize = 14
};
// Configure the text footer with page number and date
renderer.RenderingOptions.TextFooter = new TextHeaderFooter
{
LeftText = "{date}",
RightText = "Page {page} of {total-pages}",
DrawDividerLine = true,
FontSize = 10
};
// Set margins to accommodate header and footer
renderer.RenderingOptions.MarginTop = 25;
renderer.RenderingOptions.MarginBottom = 25;
// Generate PDF from HTML content
var pdf = renderer.RenderHtmlAsPdf("<h1>Sales Data</h1><p>Content goes here...</p>");
pdf.SaveAs("report-with-headers.pdf");
using IronPdf;
// Initialize the PDF renderer
var renderer = new ChromePdfRenderer();
// Configure the text header
renderer.RenderingOptions.TextHeader = new TextHeaderFooter
{
CenterText = "Quarterly Sales Report",
DrawDividerLine = true,
FontSize = 14
};
// Configure the text footer with page number and date
renderer.RenderingOptions.TextFooter = new TextHeaderFooter
{
LeftText = "{date}",
RightText = "Page {page} of {total-pages}",
DrawDividerLine = true,
FontSize = 10
};
// Set margins to accommodate header and footer
renderer.RenderingOptions.MarginTop = 25;
renderer.RenderingOptions.MarginBottom = 25;
// Generate PDF from HTML content
var pdf = renderer.RenderHtmlAsPdf("<h1>Sales Data</h1><p>Content goes here...</p>");
pdf.SaveAs("report-with-headers.pdf");
Imports IronPdf
' Initialize the PDF renderer
Dim renderer = New ChromePdfRenderer()
' Configure the text header
renderer.RenderingOptions.TextHeader = New TextHeaderFooter With {
.CenterText = "Quarterly Sales Report",
.DrawDividerLine = True,
.FontSize = 14
}
' Configure the text footer with page number and date
renderer.RenderingOptions.TextFooter = New TextHeaderFooter With {
.LeftText = "{date}",
.RightText = "Page {page} of {total-pages}",
.DrawDividerLine = True,
.FontSize = 10
}
' Set margins to accommodate header and footer
renderer.RenderingOptions.MarginTop = 25
renderer.RenderingOptions.MarginBottom = 25
' Generate PDF from HTML content
Dim pdf = renderer.RenderHtmlAsPdf("<h1>Sales Data</h1><p>Content goes here...</p>")
pdf.SaveAs("report-with-headers.pdf")
TextHeaderFooter 클래스는 헤더 또는 푸터 영역의 왼쪽, 중앙, 오른쪽에 텍스트를 배치할 수 있는 속성을 제공합니다. DrawDividerLine 속성은 헤더 또는 푸터와 주요 문서 콘텐츠 사이에 전문적인 구분선을 추가합니다. {page}, {total-pages} 및 {date}와 같은 병합 가능 필드는 PDF 생성 중에 동적 값으로 자동 채워집니다.
IronPDF는 여백 계산을 자동으로 처리하여 헤더와 푸터가 문서 콘텐츠와 겹치지 않도록 보장합니다. TextHeaderFooter 클래스는 외부 종속성 없이 타이포그래피를 제어할 수 있도록 IronSoftware.Drawing.FontTypes의 글꼴 유형을 지원합니다.
출력

전체 구현이 명확하고 읽기 쉬운 속성 할당으로 단일 코드 블록에 맞는 방식을 참고하십시오. 별도의 클래스 파일을 만들거나, 픽셀 위치를 계산하거나, 캔버스 객체를 관리할 필요가 없습니다. 이 라이브러리는 이러한 복잡성을 추상화하여 PDF 생성의 메커니즘이 아닌 콘텐츠에 집중할 수 있게 합니다.
HTML 스타일의 헤더와 푸터를 어떻게 만드나요?
보다 정교한 디자인을 위해, IronPDF의 HtmlHeaderFooter 클래스는 전체 HTML 및 CSS 스타일링을 가능하게 합니다. 이 방법은 헤더에 이미지 로고, 복잡한 레이아웃 또는 브랜드 특정 스타일을 포함해야 할 때 특히 유용합니다 - PdfPCell 개체를 수동으로 생성하거나 new Phrase 생성자를 사용하는 필요 없이.
using IronPdf;
using System;
var renderer = new ChromePdfRenderer();
// Create an HTML header with logo and styling
renderer.RenderingOptions.HtmlHeader = new HtmlHeaderFooter
{
HtmlFragment = @"
<div style='width: 100%; font-family: Arial, sans-serif;'>
<img src='logo.png' style='height: 30px; float: left;' />
<span style='float: right; font-size: 12px; color: #666;'>
Confidential Document
</span>
</div>",
MaxHeight = 25,
DrawDividerLine = true,
BaseUrl = new Uri(@"C:\assets\").AbsoluteUri
};
// Create an HTML footer with page numbering
renderer.RenderingOptions.HtmlFooter = new HtmlHeaderFooter
{
HtmlFragment = @"
<div style='text-align: center; font-size: 10px; color: #999;'>
<span>Generated on {date} at {time}</span>
<br/>
<span>Page {page} of {total-pages}</span>
</div>",
MaxHeight = 20
};
renderer.RenderingOptions.MarginTop = 30;
renderer.RenderingOptions.MarginBottom = 25;
var pdf = renderer.RenderHtmlAsPdf("<h1>Project Proposal</h1><p>Document content...</p>");
pdf.SaveAs("styled-document.pdf");
using IronPdf;
using System;
var renderer = new ChromePdfRenderer();
// Create an HTML header with logo and styling
renderer.RenderingOptions.HtmlHeader = new HtmlHeaderFooter
{
HtmlFragment = @"
<div style='width: 100%; font-family: Arial, sans-serif;'>
<img src='logo.png' style='height: 30px; float: left;' />
<span style='float: right; font-size: 12px; color: #666;'>
Confidential Document
</span>
</div>",
MaxHeight = 25,
DrawDividerLine = true,
BaseUrl = new Uri(@"C:\assets\").AbsoluteUri
};
// Create an HTML footer with page numbering
renderer.RenderingOptions.HtmlFooter = new HtmlHeaderFooter
{
HtmlFragment = @"
<div style='text-align: center; font-size: 10px; color: #999;'>
<span>Generated on {date} at {time}</span>
<br/>
<span>Page {page} of {total-pages}</span>
</div>",
MaxHeight = 20
};
renderer.RenderingOptions.MarginTop = 30;
renderer.RenderingOptions.MarginBottom = 25;
var pdf = renderer.RenderHtmlAsPdf("<h1>Project Proposal</h1><p>Document content...</p>");
pdf.SaveAs("styled-document.pdf");
Imports IronPdf
Imports System
Dim renderer As New ChromePdfRenderer()
' Create an HTML header with logo and styling
renderer.RenderingOptions.HtmlHeader = New HtmlHeaderFooter With {
.HtmlFragment = "
<div style='width: 100%; font-family: Arial, sans-serif;'>
<img src='logo.png' style='height: 30px; float: left;' />
<span style='float: right; font-size: 12px; color: #666;'>
Confidential Document
</span>
</div>",
.MaxHeight = 25,
.DrawDividerLine = True,
.BaseUrl = New Uri("C:\assets\").AbsoluteUri
}
' Create an HTML footer with page numbering
renderer.RenderingOptions.HtmlFooter = New HtmlHeaderFooter With {
.HtmlFragment = "
<div style='text-align: center; font-size: 10px; color: #999;'>
<span>Generated on {date} at {time}</span>
<br/>
<span>Page {page} of {total-pages}</span>
</div>",
.MaxHeight = 20
}
renderer.RenderingOptions.MarginTop = 30
renderer.RenderingOptions.MarginBottom = 25
Dim pdf = renderer.RenderHtmlAsPdf("<h1>Project Proposal</h1><p>Document content...</p>")
pdf.SaveAs("styled-document.pdf")
이 샘플 코드는 HTML 헤더가 텍스트 옆에 이미지를 포함할 수 있는 방법을 보여줍니다. BaseUrl 속성은 상대 이미지 URL을 해결할 수 있는 루트 경로를 설정하여 회사 로고나 기타 그래픽을 간단하게 포함할 수 있게 합니다. MaxHeight 속성은 헤더가 지정된 치수를 초과하지 않도록 하여 일관된 문서 레이아웃을 유지합니다.
병합 가능 필드 ({page}, {total-pages}, {url}, {date}, {time}, {html-title}, {pdf-title})는 HTML 헤더 및 푸터에서 동일하게 작동하여 추가 코드 없이 동적 콘텐츠 삽입을 제공합니다. 다양한 헤더 스타일 구현에 대한 안내는 헤더 및 푸터 사용 방법 안내서를 참조하십시오.
HTML 접근법은 브랜드 문서를 만드는 데 빛을 발합니다. 마케팅 팀은 개발자가 직접 통합할 수 있는 HTML 템플릿을 제공하여 승인된 디자인의 픽셀 단위 일치 재현을 보장할 수 있습니다. font-family, color, background-color 및 border과 같은 CSS 속성은 예상대로 작동하여, 다른 라이브러리에서는 광범위한 저수준 코드를 필요로 하는 정교한 시각적 처리를 가능하게 합니다.

기존 PDF 문서에 헤더를 어떻게 추가할 수 있나요?
일반적인 요구사항으로는 이미 존재하는 PDF 파일(업로드된 문서, 병합 파일, 다른 시스템에서 생성된 PDF 등)에 헤더와 푸터를 추가하는 것이 있습니다. IronPDF는 이 시나리오를 AddHtmlHeaders 및 AddHtmlFooters 메서드로 처리합니다.
using IronPdf;
// Load an existing PDF document
var pdf = PdfDocument.FromFile("customer-profile.pdf");
// Define the header to add
var header = new HtmlHeaderFooter
{
HtmlFragment = "<div style='text-align: center;'>REVISED COPY - {date}</div>",
MaxHeight = 20
};
// Define the footer to add
var footer = new HtmlHeaderFooter
{
HtmlFragment = "<div style='text-align: right;'>Page {page}</div>",
MaxHeight = 15
};
// Apply headers and footers to all pages
pdf.AddHtmlHeaders(header);
pdf.AddHtmlFooters(footer);
pdf.SaveAs("document-with-new-headers.pdf");
using IronPdf;
// Load an existing PDF document
var pdf = PdfDocument.FromFile("customer-profile.pdf");
// Define the header to add
var header = new HtmlHeaderFooter
{
HtmlFragment = "<div style='text-align: center;'>REVISED COPY - {date}</div>",
MaxHeight = 20
};
// Define the footer to add
var footer = new HtmlHeaderFooter
{
HtmlFragment = "<div style='text-align: right;'>Page {page}</div>",
MaxHeight = 15
};
// Apply headers and footers to all pages
pdf.AddHtmlHeaders(header);
pdf.AddHtmlFooters(footer);
pdf.SaveAs("document-with-new-headers.pdf");
Imports IronPdf
' Load an existing PDF document
Dim pdf = PdfDocument.FromFile("customer-profile.pdf")
' Define the header to add
Dim header As New HtmlHeaderFooter With {
.HtmlFragment = "<div style='text-align: center;'>REVISED COPY - {date}</div>",
.MaxHeight = 20
}
' Define the footer to add
Dim footer As New HtmlHeaderFooter With {
.HtmlFragment = "<div style='text-align: right;'>Page {page}</div>",
.MaxHeight = 15
}
' Apply headers and footers to all pages
pdf.AddHtmlHeaders(header)
pdf.AddHtmlFooters(footer)
pdf.SaveAs("document-with-new-headers.pdf")
PdfDocument 클래스는 로드되거나 렌더링된 PDF를 나타내며, 렌더링 후 수정 기능을 제공합니다. 렌더링과 수정의 이러한 분리는 PDF 문서가 여러 처리 단계를 거치는 워크플로우를 가능하게 합니다. AddHtmlHeaders 메서드는 자동으로 모든 페이지에 헤더를 적용하지만, 페이지 인덱스의 컬렉션을 전달하여 특정 페이지를 대상으로 지정할 수도 있습니다.
입력

출력

이 기능은 스캔 문서, 사용자 업로드 또는 서드파티 API 응답 등 다양한 출처에서 PDF 파일을 받는 문서 관리 시스템에서 매우 유용합니다. IronPDF는 배포 또는 보관 전 브랜드화 혹은 페이지 번호를 표준화합니다.
다양한 페이지에 다른 헤더를 어떻게 추가할 수 있나요?
일부 문서는 첫 페이지에 다른 헤더(또는 헤더 없음)를 필요로 하며, 이후 페이지는 표준 형식을 사용합니다. IronPDF는 페이지 인덱스 기반의 헤더 적용을 통해 이를 지원하며, void OnEndPage 핸들러 내에서 조건을 확인하거나 루프 카운터를 수동으로 관리할 필요가 없습니다:
using IronPdf;
using System.Collections.Generic;
using System.Linq;
using System.Text;
var renderer = new ChromePdfRenderer();
// Build multi-page HTML with print page-breaks between pages
var pages = new List<string>
{
"<section><h1>Title Page</h1><p>Intro text on page 1.</p></section>",
"<section><h2>Report</h2><p>Detailed report content on page 2.</p></section>",
"<section><h2>Appendix</h2><p>Appendix content on page 3.</p></section>"
};
var sb = new StringBuilder();
sb.AppendLine("<!doctype html><html><head><meta charset='utf-8'>");
sb.AppendLine("<style>");
sb.AppendLine(" body { font-family: Arial, sans-serif; margin: 20px; }");
sb.AppendLine(" .page-break { page-break-after: always; }");
sb.AppendLine("</style>");
sb.AppendLine("</head><body>");
for (int i = 0; i < pages.Count; i++)
{
sb.AppendLine(pages[i]);
if (i < pages.Count - 1)
sb.AppendLine("<div class='page-break'></div>");
}
sb.AppendLine("</body></html>");
var pdf = renderer.RenderHtmlAsPdf(sb.ToString());
// Create the standard header for pages 2 onwards
var standardHeader = new HtmlHeaderFooter
{
HtmlFragment = "<div style='text-align: center;'>Standard Header - Page {page}</div>",
MaxHeight = 20
};
// Apply to all pages except the first (index 0)
var pageIndices = Enumerable.Range(1, pdf.PageCount - 1).ToList();
pdf.AddHtmlHeaders(standardHeader, 1, pageIndices);
pdf.SaveAs("document-skip-first-page-header.pdf");
using IronPdf;
using System.Collections.Generic;
using System.Linq;
using System.Text;
var renderer = new ChromePdfRenderer();
// Build multi-page HTML with print page-breaks between pages
var pages = new List<string>
{
"<section><h1>Title Page</h1><p>Intro text on page 1.</p></section>",
"<section><h2>Report</h2><p>Detailed report content on page 2.</p></section>",
"<section><h2>Appendix</h2><p>Appendix content on page 3.</p></section>"
};
var sb = new StringBuilder();
sb.AppendLine("<!doctype html><html><head><meta charset='utf-8'>");
sb.AppendLine("<style>");
sb.AppendLine(" body { font-family: Arial, sans-serif; margin: 20px; }");
sb.AppendLine(" .page-break { page-break-after: always; }");
sb.AppendLine("</style>");
sb.AppendLine("</head><body>");
for (int i = 0; i < pages.Count; i++)
{
sb.AppendLine(pages[i]);
if (i < pages.Count - 1)
sb.AppendLine("<div class='page-break'></div>");
}
sb.AppendLine("</body></html>");
var pdf = renderer.RenderHtmlAsPdf(sb.ToString());
// Create the standard header for pages 2 onwards
var standardHeader = new HtmlHeaderFooter
{
HtmlFragment = "<div style='text-align: center;'>Standard Header - Page {page}</div>",
MaxHeight = 20
};
// Apply to all pages except the first (index 0)
var pageIndices = Enumerable.Range(1, pdf.PageCount - 1).ToList();
pdf.AddHtmlHeaders(standardHeader, 1, pageIndices);
pdf.SaveAs("document-skip-first-page-header.pdf");
Imports IronPdf
Imports System.Collections.Generic
Imports System.Linq
Imports System.Text
Dim renderer As New ChromePdfRenderer()
' Build multi-page HTML with print page-breaks between pages
Dim pages As New List(Of String) From {
"<section><h1>Title Page</h1><p>Intro text on page 1.</p></section>",
"<section><h2>Report</h2><p>Detailed report content on page 2.</p></section>",
"<section><h2>Appendix</h2><p>Appendix content on page 3.</p></section>"
}
Dim sb As New StringBuilder()
sb.AppendLine("<!doctype html><html><head><meta charset='utf-8'>")
sb.AppendLine("<style>")
sb.AppendLine(" body { font-family: Arial, sans-serif; margin: 20px; }")
sb.AppendLine(" .page-break { page-break-after: always; }")
sb.AppendLine("</style>")
sb.AppendLine("</head><body>")
For i As Integer = 0 To pages.Count - 1
sb.AppendLine(pages(i))
If i < pages.Count - 1 Then
sb.AppendLine("<div class='page-break'></div>")
End If
Next
sb.AppendLine("</body></html>")
Dim pdf = renderer.RenderHtmlAsPdf(sb.ToString())
' Create the standard header for pages 2 onwards
Dim standardHeader As New HtmlHeaderFooter With {
.HtmlFragment = "<div style='text-align: center;'>Standard Header - Page {page}</div>",
.MaxHeight = 20
}
' Apply to all pages except the first (index 0)
Dim pageIndices = Enumerable.Range(1, pdf.PageCount - 1).ToList()
pdf.AddHtmlHeaders(standardHeader, 1, pageIndices)
pdf.SaveAs("document-skip-first-page-header.pdf")
AddHtmlHeaders의 두 번째 매개변수는 {page} 병합 가능 필드를 위한 시작 페이지 번호를 지정하고, 세 번째 매개변수는 헤더를 받을 페이지 인덱스의 컬렉션을 수용합니다. 이 세밀한 제어는 복잡한 문서 레이아웃을 복잡한 조건문 로직 없이 가능하게 합니다. 고급 헤더 및 푸터 예제는 홀수/짝수 페이지 구분을 포함한 추가 시나리오를 다룹니다.
출력

페이지 번호를 넘어선 동적 콘텐츠를 어떻게 구현할 수 있나요?
병합 가능한 필드 시스템은 렌더링 중 자동으로 채워지는 여러 동적 값을 지원합니다. 다음 표는 사용할 수 있는 모든 필드와 그 의미를 나열합니다:
| 필드 | 삽입된 값 | 전형적인 사용 |
|---|---|---|
| `{page}` | 현재 페이지 번호 | "3 페이지"를 표시하는 바닥글 |
| `{total-pages}` | 총 페이지 수 | "10 중 3 페이지"를 표시하는 바닥글 |
| `{date}` | 로컬 형식의 현재 날짜 | 감사 타임스탬프, 보고서 날짜 |
| `{time}` | 로컬 형식의 현재 시간 | 규제 준수 바닥글 |
| `{html-title}` | HTML ` |
페이지 제목을 표시하는 문서 헤더 |
| `{pdf-title}` | PDF 문서 메타데이터 제목 | 문서 이름이 있는 브랜드 바닥글 |
| `{url}` | 웹 주소에서 렌더링할 때의 출처 URL | 웹 콘텐츠를 위한 아카이브 바닥글 |
실행 시점에 결정된 값으로 진정한 동적 콘텐츠를 위해, HTML 조각 문자열을 보간된 값으로 구성한 다음 HtmlFragment 속성에 할당할 수 있습니다. 이 접근 방식은 데이터베이스에서 검색한 값, 사용자 정보 또는 계산된 데이터를 포함하는 헤더를 가능하게 합니다:
using IronPdf;
string userName = GetCurrentUserName();
string documentVersion = "v2.3.1";
var renderer = new ChromePdfRenderer();
renderer.RenderingOptions.HtmlHeader = new HtmlHeaderFooter
{
HtmlFragment = $"<div style='font-size:10px;'>Prepared by: {userName} " +
$"| Version: {documentVersion} " +
"| Page {page} of {total-pages}</div>",
MaxHeight = 20
};
var pdf = renderer.RenderHtmlAsPdf("<h1>Annual Report</h1><p>Body content here.</p>");
pdf.SaveAs("dynamic-header-report.pdf");
using IronPdf;
string userName = GetCurrentUserName();
string documentVersion = "v2.3.1";
var renderer = new ChromePdfRenderer();
renderer.RenderingOptions.HtmlHeader = new HtmlHeaderFooter
{
HtmlFragment = $"<div style='font-size:10px;'>Prepared by: {userName} " +
$"| Version: {documentVersion} " +
"| Page {page} of {total-pages}</div>",
MaxHeight = 20
};
var pdf = renderer.RenderHtmlAsPdf("<h1>Annual Report</h1><p>Body content here.</p>");
pdf.SaveAs("dynamic-header-report.pdf");
Imports IronPdf
Dim userName As String = GetCurrentUserName()
Dim documentVersion As String = "v2.3.1"
Dim renderer As New ChromePdfRenderer()
renderer.RenderingOptions.HtmlHeader = New HtmlHeaderFooter With {
.HtmlFragment = $"<div style='font-size:10px;'>Prepared by: {userName} " &
$"| Version: {documentVersion} " &
"| Page {page} of {total-pages}</div>",
.MaxHeight = 20
}
Dim pdf = renderer.RenderHtmlAsPdf("<h1>Annual Report</h1><p>Body content here.</p>")
pdf.SaveAs("dynamic-header-report.pdf")
{page} 및 {total-pages} 토큰은 C# 문자열 결합 내의 단순 문자열로 남아 있으며, 보간된 부분 내에는 포함되지 않습니다. PDF 렌더링 중에 IronPDF는 이들 토큰을 자동으로 교체합니다. 이 패턴은 런타임 값에 대해 작동합니다: Active Directory의 사용자 이름, 데이터베이스의 문서 ID, 빌드 파이프라인의 버전 문자열 또는 보고 엔진의 계산된 합계.
병합 가능한 필드와 문자열 보간의 조합은 비즈니스 문서에 일반적인 정교한 바닥글 디자인을 가능하게 합니다. 법무 부서는 종종 문서 제목, 날짜 및 페이지 수를 표시하는 바닥글을 요구합니다. 금융 보고서는 규제 준수를 위한 타임스탬프가 필요할 수 있습니다. 이 요구 사항은 각 문서 유형에 대한 사용자 지정 코드 없이 충족됩니다.
iText 7 접근 방식은 어떻게 보이나요?
iText 7 (iTextSharp의 후속작)에 익숙한 개발자는 헤더와 바닥글을 추가하려면 이벤트 핸들러를 구현해야 한다는 것을 알고 있습니다. 라이브러리는 OnEndPage 및 OnCloseDocument와 같은 문서 수명 주기 이벤트에 응답하는 클래스를 생성하는 페이지 이벤트 시스템을 사용합니다.
여기 iText 7로 동일한 헤더와 푸터 구현이 ITextEvents 패턴을 사용하여 어떻게 보이는지 보여줍니다:
using iText.Kernel.Pdf;
using iText.Layout;
using iText.Layout.Element;
using iText.Kernel.Events;
using iText.Kernel.Geom;
using iText.Layout.Properties;
// Event handler class for headers and footers -- similar to PdfPageEventHelper
public class ITextEvents : IEventHandler
{
private string _header;
public string Header
{
get { return _header; }
set { _header = value; }
}
public void HandleEvent(Event currentEvent)
{
PdfDocumentEvent docEvent = (PdfDocumentEvent)currentEvent;
PdfDocument pdfDoc = docEvent.GetDocument();
PdfPage page = docEvent.GetPage();
Rectangle pageSize = page.GetPageSize();
// Create a new PdfCanvas for the contentbyte object
PdfCanvas pdfCanvas = new PdfCanvas(
page.NewContentStreamBefore(),
page.GetResources(),
pdfDoc);
Canvas canvas = new Canvas(pdfCanvas, pageSize);
// Add header text at calculated position
canvas.ShowTextAligned(
new Paragraph("Quarterly Sales Report"),
pageSize.GetWidth() / 2,
pageSize.GetTop() - 20,
TextAlignment.CENTER);
// Add footer with page number
int pageNumber = pdfDoc.GetPageNumber(page);
canvas.ShowTextAligned(
new Paragraph($"Page {pageNumber}"),
pageSize.GetWidth() / 2,
pageSize.GetBottom() + 20,
TextAlignment.CENTER);
canvas.Close();
}
}
// Usage in main code
var writer = new PdfWriter("report.pdf");
var pdfDoc = new PdfDocument(writer);
var document = new Document(pdfDoc);
// Register the event handler for END_PAGE
pdfDoc.AddEventHandler(PdfDocumentEvent.END_PAGE, new ITextEvents());
document.Add(new Paragraph("Sales Data"));
document.Add(new Paragraph("Content goes here..."));
document.Close();
using iText.Kernel.Pdf;
using iText.Layout;
using iText.Layout.Element;
using iText.Kernel.Events;
using iText.Kernel.Geom;
using iText.Layout.Properties;
// Event handler class for headers and footers -- similar to PdfPageEventHelper
public class ITextEvents : IEventHandler
{
private string _header;
public string Header
{
get { return _header; }
set { _header = value; }
}
public void HandleEvent(Event currentEvent)
{
PdfDocumentEvent docEvent = (PdfDocumentEvent)currentEvent;
PdfDocument pdfDoc = docEvent.GetDocument();
PdfPage page = docEvent.GetPage();
Rectangle pageSize = page.GetPageSize();
// Create a new PdfCanvas for the contentbyte object
PdfCanvas pdfCanvas = new PdfCanvas(
page.NewContentStreamBefore(),
page.GetResources(),
pdfDoc);
Canvas canvas = new Canvas(pdfCanvas, pageSize);
// Add header text at calculated position
canvas.ShowTextAligned(
new Paragraph("Quarterly Sales Report"),
pageSize.GetWidth() / 2,
pageSize.GetTop() - 20,
TextAlignment.CENTER);
// Add footer with page number
int pageNumber = pdfDoc.GetPageNumber(page);
canvas.ShowTextAligned(
new Paragraph($"Page {pageNumber}"),
pageSize.GetWidth() / 2,
pageSize.GetBottom() + 20,
TextAlignment.CENTER);
canvas.Close();
}
}
// Usage in main code
var writer = new PdfWriter("report.pdf");
var pdfDoc = new PdfDocument(writer);
var document = new Document(pdfDoc);
// Register the event handler for END_PAGE
pdfDoc.AddEventHandler(PdfDocumentEvent.END_PAGE, new ITextEvents());
document.Add(new Paragraph("Sales Data"));
document.Add(new Paragraph("Content goes here..."));
document.Close();
Imports iText.Kernel.Pdf
Imports iText.Layout
Imports iText.Layout.Element
Imports iText.Kernel.Events
Imports iText.Kernel.Geom
Imports iText.Layout.Properties
' Event handler class for headers and footers -- similar to PdfPageEventHelper
Public Class ITextEvents
Implements IEventHandler
Private _header As String
Public Property Header As String
Get
Return _header
End Get
Set(value As String)
_header = value
End Set
End Property
Public Sub HandleEvent(currentEvent As [Event]) Implements IEventHandler.HandleEvent
Dim docEvent As PdfDocumentEvent = CType(currentEvent, PdfDocumentEvent)
Dim pdfDoc As PdfDocument = docEvent.GetDocument()
Dim page As PdfPage = docEvent.GetPage()
Dim pageSize As Rectangle = page.GetPageSize()
' Create a new PdfCanvas for the contentbyte object
Dim pdfCanvas As New PdfCanvas(page.NewContentStreamBefore(), page.GetResources(), pdfDoc)
Dim canvas As New Canvas(pdfCanvas, pageSize)
' Add header text at calculated position
canvas.ShowTextAligned(New Paragraph("Quarterly Sales Report"), pageSize.GetWidth() / 2, pageSize.GetTop() - 20, TextAlignment.CENTER)
' Add footer with page number
Dim pageNumber As Integer = pdfDoc.GetPageNumber(page)
canvas.ShowTextAligned(New Paragraph($"Page {pageNumber}"), pageSize.GetWidth() / 2, pageSize.GetBottom() + 20, TextAlignment.CENTER)
canvas.Close()
End Sub
End Class
' Usage in main code
Dim writer As New PdfWriter("report.pdf")
Dim pdfDoc As New PdfDocument(writer)
Dim document As New Document(pdfDoc)
' Register the event handler for END_PAGE
pdfDoc.AddEventHandler(PdfDocumentEvent.END_PAGE, New ITextEvents())
document.Add(New Paragraph("Sales Data"))
document.Add(New Paragraph("Content goes here..."))
document.Close()
이 구현은 두 라이브러리 간의 근본적인 아키텍처 차이를 보여줍니다. iText 7은 IEventHandler을 구현하는 별도의 핸들러 클래스를 생성해야 하며 (레거시 PdfPageEventHelper과 유사), 부동 소수 좌표를 사용하여 페이지 위치를 수동으로 계산하고, 그리기 작업을 위한 PdfCanvas 및 Canvas 객체를 관리해야 합니다. 핸들러는 페이지당 이벤트를 END_PAGE 이벤트 유형을 통해 수신하며, 많은 개발자가 잘못 사용하여 오류를 범하는 START_PAGE를 사용하지 마십시오.
출력

iText 7의 좌표 시스템은 페이지의 왼쪽 하단 모서리에서 시작하여, 위치를 잡기 위한 명시적 계산이 필요합니다. 최종 페이지 수를 얻으려면 PdfTemplate 패턴을 통해 추가적인 복잡성이 필요하며, 이는 OnCloseDocument 동안 채워지는 패턴으로, 이미 복잡한 워크플로에 추가적인 보일러플레이트 코드를 추가하는 패턴입니다.
웹 개발 배경의 개발자들에게 이 좌표 기반 접근 방식은 선언적 HTML/CSS 모델과는 상이하게 느껴집니다. 각 위치 결정은 페이지 크기, 여백 오프셋 및 텍스트 측정을 이해하는 것이 필요하며, 이는 HTML 기반 접근 방식에서는 추상화됩니다.
iText 7은 또한 AGPL 라이선스 하에 운영되며, iTextSharp 또는 iText 7을 사용하는 애플리케이션은 상업적 라이선스를 구매하지 않으면 오픈 소스여야 합니다. 이는 상용 프로젝트를 위한 라이브러리를 선택할 때 중요한 사항입니다.
두 접근 방식은 어떻게 비교됩니까?
특정 기능을 나란히 볼 때 차이점이 더 명확해집니다. 다음 표는 주요 차이점을 요약합니다:
| 특징 | IronPDF | iText 7 / iTextSharp |
|---|---|---|
| 구현 스타일 | 렌더러 옵션에서 속성 할당 | IEventHandler를 구현하는 이벤트 핸들러 클래스 |
| HTML/CSS 지원 | HtmlHeaderFooter를 통한 전체 HTML 및 CSS | 기본 HTML 지원 없음; 저수준 캔버스 그리기 필요 |
| 페이지 번호 합계 | `{total-pages}` 필드를 통한 자동화 | OnCloseDocument에서 PdfTemplate을 채워야 함 |
| 헤더의 이미지 | BaseUrl로 표준 HTML ` |
이미지 객체 및 수동 위치 지정 필요 |
| 기존 PDF에 추가 | AddHtmlHeaders / AddHtmlFooters 메서드 | 스탬퍼 또는 이벤트 루프를 통해 재처리 필요 |
| 페이지별 타겟팅 | 메서드에 전달된 페이지 인덱스 목록 | 이벤트 핸들러 내부의 조건부 논리 |
| 라이선스 모델 | 무료 체험 제공 상업용 | AGPL (오픈 소스) 또는 상업적 |
| 크로스 플랫폼 | 윈도우, 리눅스, macOS; Docker 준비 완료 | 윈도우, 리눅스, macOS |
문제를 해결할 때 개발 경험도 크게 다릅니다. IronPDF의 HTML 기반 접근 방식은 PDF 생성 코드를 통합하기 전에 브라우저에서 헤더 디자인을 미리 볼 수 있다는 것을 의미합니다. 문제가 있는 경우 익숙한 브라우저 개발자 도구로 HTML 및 CSS를 조정할 수 있습니다. iText 7에서는 위치 지정 문제를 디버깅하려면 테스트 PDF를 반복적으로 생성하고 좌표를 수동으로 측정해야 합니다.
HTML 기반 접근 방식은 기존 웹 개발 기술을 직접 적용할 수 있음을 의미합니다. HTML 및 CSS로 달성 가능한 모든 레이아웃은 IronPDF 헤더 및 푸터에서 작동하며, 플렉스박스 배열에서 이미지 그리드까지 가능합니다. HTML Headers and Footers 예제는 추가적인 스타일링 가능성을 보여줍니다.
헤더 및 푸터 모양 사용자 정의
헤더 및 푸터의 세부 조정에는 위치 및 시각적 표현에 영향을 미치는 여러 속성이 포함됩니다. TextHeaderFooter 클래스는 이러한 사용자 정의 옵션을 제공합니다:
using IronPdf;
using IronSoftware.Drawing;
var renderer = new ChromePdfRenderer();
var footer = new TextHeaderFooter
{
LeftText = "Confidential",
CenterText = "{pdf-title}",
RightText = "Page {page} of {total-pages}",
Font = FontTypes.Arial,
FontSize = 9,
DrawDividerLine = true,
DrawDividerLineColor = Color.Gray
};
renderer.RenderingOptions.TextFooter = footer;
renderer.RenderingOptions.MarginBottom = 20;
var pdf = renderer.RenderHtmlAsPdf("<h1>Board Report</h1><p>Executive summary content.</p>");
pdf.SaveAs("board-report.pdf");
using IronPdf;
using IronSoftware.Drawing;
var renderer = new ChromePdfRenderer();
var footer = new TextHeaderFooter
{
LeftText = "Confidential",
CenterText = "{pdf-title}",
RightText = "Page {page} of {total-pages}",
Font = FontTypes.Arial,
FontSize = 9,
DrawDividerLine = true,
DrawDividerLineColor = Color.Gray
};
renderer.RenderingOptions.TextFooter = footer;
renderer.RenderingOptions.MarginBottom = 20;
var pdf = renderer.RenderHtmlAsPdf("<h1>Board Report</h1><p>Executive summary content.</p>");
pdf.SaveAs("board-report.pdf");
Imports IronPdf
Imports IronSoftware.Drawing
Dim renderer As New ChromePdfRenderer()
Dim footer As New TextHeaderFooter With {
.LeftText = "Confidential",
.CenterText = "{pdf-title}",
.RightText = "Page {page} of {total-pages}",
.Font = FontTypes.Arial,
.FontSize = 9,
.DrawDividerLine = True,
.DrawDividerLineColor = Color.Gray
}
renderer.RenderingOptions.TextFooter = footer
renderer.RenderingOptions.MarginBottom = 20
Dim pdf = renderer.RenderHtmlAsPdf("<h1>Board Report</h1><p>Executive summary content.</p>")
pdf.SaveAs("board-report.pdf")
Font 속성은 IronSoftware.Drawing.FontTypes에서 제공하는 값을 허용하며, 헬베티카, 아리아, 쿠리어, 타임즈 뉴로만 등을 포함합니다. DrawDividerLine 속성은 푸터와 본문 내용 사이에 전문적인 수평선을 추가합니다. DrawDividerLineColor을 사용하여 선 색상을 조정하여 브랜드 색상이나 문서 테마에 맞출 수 있습니다.
HTML 기반의 헤더 및 푸터의 경우, LoadStylesAndCSSFromMainHtmlDocument 속성은 렌더링 중인 주요 문서의 스타일을 선택적으로 상속하여 헤더와 본문 콘텐츠 간의 시각적 일관성을 보장합니다. 이는 주요 문서가 사용자 정의 CSS를 사용할 때 특히 유용하며, 이는 헤더 및 푸터 영역에도 적용되어야 합니다.

크로스 플랫폼 및 컨테이너 배포
현대 .NET 응용 프로그램은 종종 Linux 컨테이너, Azure App Services 또는 AWS Lambda 함수에 배포됩니다. IronPDF는 추가 구성 없이 Windows, Linux 및 macOS 전반에 걸쳐 크로스 플랫폼 배포를 지원합니다. 라이브러리는 기본적으로 Docker 컨테이너에서 작동하므로 마이크로서비스 아키텍처 및 클라우드 네이티브 응용 프로그램에 적합합니다.
이 크로스 플랫폼 기능은 헤더 및 푸터 기능으로 확장되며, Windows 개발 머신에서 헤더와 함께 PDF를 생성하는 동일한 코드는 Linux 프로덕션 서버에 배포되었을 때 동일한 출력을 생성합니다. 추가 폰트를 설치하거나 렌더링 엔진을 구성하거나 플랫폼별 코드 경로를 처리할 필요가 없습니다.
컨테이너 된 작업 부하를 실행하는 팀을 위해, IronPDF Docker 배포 문서는 다양한 기본 이미지 및 오케스트레이션 플랫폼에 대한 구성 가이드를 제공합니다. 라이브러리의 환경 간 일관된 동작은 PDF 생성 워크플로에서 버그의 일반적인 원인을 제거합니다.
Microsoft의 .NET 문서에 따르면, 컨테이너 된 .NET 응용 프로그램은 환경 전반의 일관된 런타임 동작의 이점을 제공합니다 -- PDF 생성 작업을 위한 IronPDF의 렌더링 엔진이 강화하는 원칙입니다. 마찬가지로, Docker의 공식 문서는 PDF 생성 서비스에 직접 적용되는 .NET 작업 부하를 컨테이너화하는 모범 사례를 설명합니다.
iText 7 문서는 크로스 플랫폼 지원을 확인하지만, 이벤트 구동 모델의 추가적인 복잡성은 HTML 기반 선언적 접근 방식보다 크로스 플랫폼 렌더링 문제의 디버깅이 더 복잡할 수 있습니다.
다음 단계는 무엇입니까?
IronPDF를 사용하여 PDF 문서에 헤더 및 푸터를 구현하는 데 몇 분밖에 걸리지 않습니다. NuGet 패키지 관리자를 통해 라이브러리를 설치하십시오:
Install-Package IronPdf
dotnet add package IronPdf
Install-Package IronPdf
dotnet add package IronPdf

여기에서, 이러한 리소스는 더 나아가는데 도움이 될 것입니다:
- 시작하기 문서 -- 전체 PDF 생성 및 조작 기능을 다룹니다
- 헤더 및 푸터 사용 설명서 -- 모든 헤더 및 푸터 시나리오에 대한 단계별 지침
- HTML 헤더 및 푸터 예제 -- HTML 기반 헤더에 대한 실행 가능한 코드 샘플
- 고급 헤더 및 푸터 예제 -- 페이지별 타겟팅 및 홀/짝수 페이지 구분
- TextHeaderFooter API 참조 -- 텍스트 기반 헤더 및 푸터에 대한 전체 속성 목록
- HtmlHeaderFooter API 참조 -- HTML 기반 머리글 및 바닥글을 위한 전체 API
- Docker 배포 가이드 -- Linux 컨테이너 및 클라우드 환경을 위한 구성
- IronPDF 라이선스 옵션 -- 개인 개발자부터 기업 팀까지의 계획
무료 체험판 시작하기하여 귀하의 프로젝트에서 머리글 및 바닥글 구현을 테스트하십시오. 체험판은 모든 기능을 포함하며 기능에 대한 시간 제한이 없으므로 라이선스를 결정하기 전에 실제 PDF 문서 요구 사항과 비교하여 라이브러리를 평가할 수 있습니다.

C#에서 PDF 문서에 머리글 및 바닥글을 추가하는 것은 선택한 라이브러리에 따라 간단할 수도 복잡할 수도 있습니다. iText 7은 이벤트 핸들러와 캔버스 작업을 통해 저수준의 제어를 제공하지만, IronPDF는 친숙한 HTML 및 CSS 개념을 적용하는 API를 통해 동일한 기능을 제공합니다. 빠른 구현과 유지 보수 가능한 코드를 우선시하는 개발자에게 IronPDF는 수십 줄의 코드, 핸들러 클래스, 셀 구성 및 테이블 구조를 단 몇 가지 속성 할당으로 감소시킵니다.
자주 묻는 질문
iTextSharp를 사용하여 PDF에 헤더와 푸터를 추가할 수 있는 방법은?
iTextSharp를 사용하여 PDF에 헤더와 푸터를 추가하려면, PDF 생성 과정에서 문서의 페이지를 사용자 정의할 수 있는 페이지 이벤트 핸들러를 정의할 수 있습니다. 이는 원하는 헤더와 푸터 내용을 포함하도록 OnEndPage 메소드를 재정의하는 것을 포함합니다.
IronPDF를 사용하여 헤더와 푸터를 추가하는 것의 장점은 무엇입니까?
IronPDF는 간단한 API를 제공하여 헤더와 푸터를 추가하는 과정을 단순화하고 다양한 스타일링 옵션을 지원합니다. C# 프로젝트와 매끄럽게 통합되며, HTML을 PDF로 변환하는 기능 등 추가 기능을 제공하여 PDF 조작에 유용한 도구가 됩니다.
IronPDF와 iTextSharp를 함께 사용할 수 있습니까?
예, IronPDF와 iTextSharp를 C# 프로젝트에서 함께 사용할 수 있습니다. iTextSharp는 프로그래밍으로 PDF를 조작하는데 탁월하며, IronPDF는 HTML을 PDF로 변환하는 등의 추가 기능을 제공하여 이를 보완합니다. 이는 헤더와 푸터를 동적으로 생성하는 데 유용할 수 있습니다.
IronPDF를 사용하여 헤더와 푸터를 스타일링할 수 있는 방법이 있습니까?
IronPDF는 HTML과 CSS를 사용하여 헤더와 푸터를 스타일링할 수 있게 해줍니다. 이는 개발자에게 PDF 문서를 위한 매력적인 디자인과 레이아웃을 만들 수 있는 유연성을 제공합니다.
IronPDF는 헤더와 푸터에 페이지 번호를 어떻게 처리합니까?
IronPDF는 자동으로 헤더와 푸터에 페이지 번호를 삽입할 수 있습니다. 이는 페이지 번호의 포맷을 필요에 맞게 조정할 수 있는 옵션을 제공하며, 총 페이지 수 포함이나 시작 페이지 번호의 조정 등을 포함할 수 있습니다.
IronPDF를 사용하여 C#으로 PDF를 조작할 때의 장점은 무엇입니까?
IronPDF를 사용하여 C#으로 PDF를 조작할 때 강력한 타입 안정성, .NET 애플리케이션과의 쉬운 통합, 개발 과정을 개선하는 폭넓은 라이브러리와 도구에 접근할 수 있다는 장점이 있습니다. IronPDF의 C# API는 직관적이고 사용자 친화적으로 설계되어 있어, 모든 수준의 개발자가 접근하기 용이합니다.
IronPDF를 사용하여 기존 문서를 PDF로 변환할 수 있습니까?
네, IronPDF는 HTML, ASPX 등의 웹 기반 콘텐츠를 포함한 다양한 문서 형식을 PDF로 변환할 수 있습니다. 이 기능은 특히 웹 페이지 또는 동적으로 생성된 콘텐츠로부터 PDF를 만들 때 유용합니다.


