반응형
1. 강의 개요
이번 강의에서는 iTextSharp 라이브러리를 사용해 PDF 파일을 생성하고 읽는 방법을 배웁니다.
PDF는 문서 공유에 널리 사용되는 형식으로,
텍스트와 표, 이미지 등을 포함한 PDF 파일을 손쉽게 생성 및 읽을 수 있습니다.
실습에서는 PDF 파일에 텍스트와 표를 추가하고,
작성된 PDF 파일을 읽어와 내용을 표시하는 애플리케이션을 제작합니다.
2. 학습 목표
- iTextSharp을 사용해 PDF 파일 생성
- PDF 파일에 텍스트와 표 추가
- PDF 파일 읽기 및 내용 표시
- 파일 열기 및 저장 대화 상자 구현
3. 기능 요구사항
필수 기능
1️⃣ PDF 파일 생성:
- 텍스트, 표, 이미지가 포함된 PDF 파일 생성
2️⃣ PDF 파일 읽기:
- 기존 PDF 파일을 읽어 텍스트를 추출
3️⃣ UI 구성 및 동작:
- PDF 생성 및 읽기 기능을 UI에서 실행
4. 실습: PDF 파일 생성 및 읽기 애플리케이션 제작
1️⃣ 사전 준비
- NuGet 패키지 설치:
- Visual Studio에서 iTextSharp 패키지를 설치합니다.
- 설치 명령: Install-Package itext7
- 폼 구성:
- 폼(Form) 이름: Form1
- 컨트롤 배치:
컨트롤 타입 이름 위치 크기
Button | btnCreatePdf | 폼 상단 왼쪽 | (150 x 30) |
Button | btnReadPdf | 폼 상단 오른쪽 | (150 x 30) |
TextBox | txtContent | 폼 하단 전체 | (500 x 300) |
📌 폼 디자인 예시:
--------------------------------------------------
| [Create PDF 버튼] [Read PDF 버튼] |
--------------------------------------------------
| [TextBox - PDF 내용 표시] |
--------------------------------------------------
2️⃣ 코드 작성
(1) PDF 파일 생성
using System;
using System.IO;
using System.Windows.Forms;
using iText.Kernel.Pdf;
using iText.Layout;
using iText.Layout.Element;
namespace WindowsFormsApp_PDF
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
// PDF 파일 생성
private void btnCreatePdf_Click(object sender, EventArgs e)
{
using (SaveFileDialog saveFileDialog = new SaveFileDialog())
{
saveFileDialog.Filter = "PDF 파일 (*.pdf)|*.pdf";
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
string filePath = saveFileDialog.FileName;
CreatePdf(filePath);
}
}
}
private void CreatePdf(string filePath)
{
try
{
using (var writer = new PdfWriter(filePath))
using (var pdf = new PdfDocument(writer))
{
var document = new Document(pdf);
// 텍스트 추가
document.Add(new Paragraph("iTextSharp로 생성한 PDF 파일입니다."));
document.Add(new Paragraph("다음은 표 예제입니다."));
// 표 추가
var table = new Table(3);
table.AddCell("Header 1");
table.AddCell("Header 2");
table.AddCell("Header 3");
for (int i = 1; i <= 9; i++)
{
table.AddCell($"Cell {i}");
}
document.Add(table);
document.Close();
MessageBox.Show("PDF 파일이 생성되었습니다.", "완료", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
catch (Exception ex)
{
MessageBox.Show($"PDF 생성 실패: {ex.Message}", "오류", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
(2) PDF 파일 읽기
// PDF 파일 읽기
private void btnReadPdf_Click(object sender, EventArgs e)
{
using (OpenFileDialog openFileDialog = new OpenFileDialog())
{
openFileDialog.Filter = "PDF 파일 (*.pdf)|*.pdf";
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
string filePath = openFileDialog.FileName;
ReadPdf(filePath);
}
}
}
private void ReadPdf(string filePath)
{
try
{
using (var reader = new PdfReader(filePath))
using (var pdf = new PdfDocument(reader))
{
var text = string.Empty;
for (int i = 1; i <= pdf.GetNumberOfPages(); i++)
{
text += pdf.GetPage(i).GetTextContent().GetText();
}
txtContent.Text = text;
MessageBox.Show("PDF 파일을 성공적으로 읽었습니다.", "완료", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
catch (Exception ex)
{
MessageBox.Show($"PDF 읽기 실패: {ex.Message}", "오류", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
(3) Designer 코드
private void InitializeComponent()
{
this.btnCreatePdf = new Button();
this.btnReadPdf = new Button();
this.txtContent = new TextBox();
// Create PDF Button 설정
this.btnCreatePdf.Location = new System.Drawing.Point(10, 10);
this.btnCreatePdf.Size = new System.Drawing.Size(150, 30);
this.btnCreatePdf.Text = "Create PDF";
this.btnCreatePdf.Click += new EventHandler(this.btnCreatePdf_Click);
// Read PDF Button 설정
this.btnReadPdf.Location = new System.Drawing.Point(170, 10);
this.btnReadPdf.Size = new System.Drawing.Size(150, 30);
this.btnReadPdf.Text = "Read PDF";
this.btnReadPdf.Click += new EventHandler(this.btnReadPdf_Click);
// TextBox 설정
this.txtContent.Location = new System.Drawing.Point(10, 50);
this.txtContent.Size = new System.Drawing.Size(500, 300);
this.txtContent.Multiline = true;
this.txtContent.ScrollBars = ScrollBars.Vertical;
// Form 설정
this.ClientSize = new System.Drawing.Size(540, 400);
this.Controls.Add(this.btnCreatePdf);
this.Controls.Add(this.btnReadPdf);
this.Controls.Add(this.txtContent);
this.Text = "PDF 생성 및 읽기 애플리케이션";
}
3️⃣ 실행 결과
1️⃣ PDF 파일 생성
- "Create PDF" 버튼 클릭 → 저장 경로 선택 → PDF 파일 생성
2️⃣ PDF 파일 읽기
- "Read PDF" 버튼 클릭 → PDF 파일 선택 → TextBox에 PDF 내용 표시
5. 주요 개념 요약
- iTextSharp: PDF 파일 생성 및 읽기 기능을 제공하는 라이브러리
- PdfWriter & PdfReader: PDF 파일 쓰기 및 읽기 처리 클래스
- Table: PDF 파일에 표 추가
- Paragraph: 텍스트 추가를 위한 클래스
📌 #CSharp #WindowsForms #PDF #iTextSharp #PDF생성 #PDF읽기
반응형
'📁 [4] 개발자 정보 & 코드 노트 > C#' 카테고리의 다른 글
C# Windows Forms 강의 80편: 비디오 처리 및 실시간 스트리밍 - OpenCvSharp 활용 (0) | 2025.04.23 |
---|---|
C# Windows Forms 강의 79편: 이미지 처리 애플리케이션 제작 - OpenCvSharp 활용 (0) | 2025.04.22 |
C# Windows Forms 강의 76편: CSV 데이터를 기반으로 한 데이터 분석 애플리케이션 (0) | 2025.04.20 |
C# Windows Forms 강의 75편: 실시간 대시보드 - 센서 데이터를 활용한 시각화 (0) | 2025.04.19 |
C# Windows Forms 강의 74편: MQTT 프로토콜을 활용한 IoT 애플리케이션 제작 (0) | 2025.04.18 |