C#를 사용하여 PDF 문서에 페이지 번호 추가
Source: Dev.to
Introduction
PDF 문서는 정보 교환 및 저장을 위한 보편적인 포맷으로, 일상적인 사무 작업 및 기술 문서에 필수적입니다. 많은 PDF에 페이지 번호를 수동으로 추가하는 것은 번거롭고 시간이 많이 소요됩니다. C#와 서드파티 라이브러리 Spire.PDF for .NET을 사용해 이 과정을 자동화하면 각 페이지 하단에 “Page X of Y” 형식의 페이지 번호를 빠르고 전문적으로 추가할 수 있습니다.
Installing Spire.PDF for .NET
Spire.PDF for .NET은 Adobe Acrobat 없이도 개발자가 PDF 문서를 생성, 읽기, 편집, 변환 및 인쇄할 수 있게 해 주는 전문 .NET PDF 컴포넌트입니다.
NuGet Package Manager Console
Install-Package Spire.PDF
NuGet Package Manager UI
- Visual Studio에서 프로젝트를 마우스 오른쪽 버튼으로 클릭합니다.
- **Manage NuGet Packages…**를 선택합니다.
- Browse 탭에서 Spire.PDF를 검색합니다.
- Install를 클릭합니다.
설치가 완료되면 Spire.PDF에 대한 참조가 자동으로 추가되며, 바로 API를 사용할 수 있습니다.
Adding Centered “Page X of Y” Numbers
다음 단계에서는 PDF를 로드하고, 페이지 번호용 복합 필드를 생성한 뒤, 각 페이지의 하단 중앙에 배치하고, 수정된 문서를 저장하는 방법을 설명합니다.
1. Load the Document
PdfDocument를 사용해 대상 PDF를 엽니다.
2. Get Total Page Count
doc.Pages.Count를 가져와 “of Y” 부분을 구성합니다.
3. Iterate Through Pages
각 페이지를 순회하면서 그리기 위치를 계산하고 페이지 번호를 렌더링합니다.
4. Save the Document
결과를 새로운 PDF 파일에 저장합니다.
Complete Example (C#)
using Spire.Pdf;
using Spire.Pdf.AutomaticFields;
using Spire.Pdf.Graphics;
using System.Drawing;
using Spire.Pdf.License;
namespace AddPageNumbersToCenter
{
class Program
{
static void Main(string[] args)
{
// Apply your license key
LicenseProvider.SetLicenseKey("License Key");
// Load the PDF file
PdfDocument doc = new PdfDocument();
doc.LoadFromFile(@"C:\Users\Administrator\Desktop\Terms of service.pdf");
// Define appearance of the page number
PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Times New Roman", 12, FontStyle.Regular), true);
PdfBrush brush = PdfBrushes.Black;
PdfPen pen = new PdfPen(brush, 1.0f);
// Create fields for page number and total page count
PdfPageNumberField pageNumberField = new PdfPageNumberField();
PdfPageCountField pageCountField = new PdfPageCountField();
// Composite field combines the two fields with the desired format
PdfCompositeField compositeField = new PdfCompositeField(
font, brush, "Page {0} of {1}", pageNumberField, pageCountField);
// Add the composite field to each page
for (int i = 0; i < doc.Pages.Count; i++)
{
PdfPageBase page = doc.Pages[i];
SizeF pageSize = page.Size;
// Optional: draw a separator line
page.Canvas.DrawLine(pen, 72, pageSize.Height - 50, pageSize.Width - 72, pageSize.Height - 50);
// Measure the width of the page number string
SizeF pageNumberSize = font.MeasureString(
string.Format("Page {0} of {1}", i + 1, doc.Pages.Count));
// Center the composite field at the bottom
compositeField.Location = new PointF(
(pageSize.Width - pageNumberSize.Width) / 2,
pageSize.Height - 45);
// Render the field
compositeField.Draw(page.Canvas);
}
// Save the modified PDF
doc.SaveToFile("AddPageNumbersToCenter.pdf");
doc.Dispose();
}
}
}
Key Code Explanations
| Code | Explanation |
|---|---|
doc.LoadFromFile(@"C:\...\Terms of service.pdf"); | 소스 PDF를 로드합니다. |
doc.Pages.Count | 전체 페이지 수를 가져옵니다. |
PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Times New Roman", 12, FontStyle.Regular), true); | 12 pt Times New Roman 폰트를 생성합니다. |
PdfBrush brush = PdfBrushes.Black; | 텍스트 색상을 검은색으로 설정합니다. |
PdfCompositeField compositeField = new PdfCompositeField(font, brush, "Page {0} of {1}", pageNumberField, pageCountField); | “Page X of Y” 필드를 구성합니다. |
compositeField.Location = new PointF((pageSize.Width - pageNumberSize.Width) / 2, pageSize.Height - 45); | 필드를 가로 중앙에 배치하고 하단 근처에 위치시킵니다. |
compositeField.Draw(page.Canvas); | 현재 페이지에 필드를 그립니다. |
doc.SaveToFile("AddPageNumbersToCenter.pdf"); | 페이지 번호가 추가된 새 PDF를 저장합니다. |
Customizing Page Numbers
Spire.PDF for .NET은 다음과 같은 높은 유연성을 제공합니다:
- Positioning –
Location을 조정해 수직·수평 위치를 변경합니다. - Font Styles & Colors – 원하는
PdfTrueTypeFont와PdfBrush를 사용합니다. - Formats – 포맷 문자열을 변경합니다(예:
"Page {0}","第{0}页/共{1}页"). - Different Page Sizes – 루프 내에서 페이지 크기에 따라 위치를 다시 계산합니다.
- Additional Effects – 워터마크, 헤더, 푸터 또는 다른 자동 필드와 결합할 수 있습니다.
Conclusion
이 튜토리얼을 따라 하면 C#와 Spire.PDF for .NET을 사용해 PDF 문서에 “Page X of Y” 번호를 자동으로 추가할 수 있습니다. 수동으로 하던 오류가 잦은 작업을 없애고 PDF의 전문성과 가독성을 크게 향상시킵니다. 라이브러리의 다른 기능(워터마크, 주석, 변환 등)도 탐색해 문서 처리 애플리케이션을 더욱 강화해 보세요.