C#에서 PDF 파일을 저장하는 방법 (초보자 튜토리얼)
이 문서에서는 Windows Forms Application이나 어떤 .NET 애플리케이션에서 IronPDF를 사용하여 PDF 파일을 저장하는 방법을 탐색할 것입니다.
IronPDF 라이브러리는 C# 애플리케이션에서 PDF 파일을 생성하고 작업하기 위한 사용하기 쉬운 클래스와 메서드를 제공하는 .NET 라이브러리입니다. 개발자가 몇 줄의 코드만으로 PDF 파일을 생성, 수정, 저장할 수 있으므로 Windows Forms 애플리케이션에 탁월한 선택입니다.
단계 1: 새로운 Windows Forms 애플리케이션 생성하기
먼저 새 Visual Studio 프로젝트를 만드십시오. Visual Studio 2022에서 새로운 C# Windows Forms Application을 생성하는 단계는 다음과 같습니다
- 아래와 같이 Visual Studio 2022를 엽니다.
Visual Studio 2022
- 시작 페이지에서 "새 프로젝트 만들기"를 클릭하거나 "파일" > "새로 만들기" > "프로젝트"로 이동합니다.
- "새 프로젝트 만들기" 대화 상자에서 아래와 같이 "새 프로젝트 만들기" 아래에서 "윈도우 폼 앱" 또는 "윈도우 폼 앱 (.NET Framework)"를 선택합니다.
새 폼 앱
- 프로젝트의 이름을 입력하고 저장할 위치를 선택하세요.
프로젝트 위치
- .NET Framework를 선택하세요. .NET 7.0을 드롭다운 메뉴에서 선택하세요.
- 생성하기 버튼을 클릭합니다.
추가 정보
- Visual Studio는 기본 폼 "Form1"이 프로젝트에 추가된 상태로 새로운 C# Windows Forms Application 프로젝트를 생성합니다.
Form1 프로젝트
그게 다예요! 이제 디자이너를 사용하여 Windows Forms Application을 구축하고, PDF 문서 파일을 생성하고 저장하기 위한 컨트롤과 기능을 추가할 것입니다.
단계 2: 폼 디자인하기
사용자의 선호에 따라 폼을 디자인할 수 있습니다. 이 튜토리얼에서는 두 개의 레이블, 하나의 리치 텍스트 박스, 두 개의 버튼을 추가하여 최소한의 디자인을 만들 것입니다.
양식에 버튼 추가하기
3단계: IronPDF 설치하기
다음 단계는 이 프로젝트에 IronPDF를 설치하여 강력한 기능을 사용하는 것입니다.
IronPDF는 Visual Studio의 NuGet 패키지 관리자를 사용하여 설치할 수 있습니다. 도구 > NuGet 패키지 관리자 > 패키지 관리자 콘솔로 이동하여 NuGet 패키지 관리자 콘솔을 탐색할 수 있습니다.
다음 명령을 입력하고 Enter 키를 누르세요:
Install-Package IronPdf
이 명령어는 프로젝트에 IronPDF 패키지를 다운로드하고 설치합니다. 설치가 완료되면 IronPDF를 사용할 수 있습니다.
코드를 작성하여 PDF 파일 생성 및 저장하기
프로세스를 시작하려면 Save_Click 및 getFilePath 메소드를 Form1.cs 클래스에 작성합니다. 이들 메서드는 텍스트 박스의 내용을 PDF 파일로 저장하기 위해 ChromePdfRenderer Class 라이브러리를 함께 사용합니다. 각 메서드를 검토하여 어떻게 작동하는지 이해해 보겠습니다.
Save_Click 메서드 (PDF 문서 생성)
다음 메서드는 버튼 클릭 이벤트의 이벤트 핸들러입니다. 이 메서드의 목적은 텍스트 박스의 내용을 PDF 파일로 저장하는 것입니다.
private void Save_Click(object sender, EventArgs e)
{
// Get the file path to save the PDF file.
string filename = getFilePath();
// If the file path is not empty or null, proceed with saving the PDF file.
if (!String.IsNullOrEmpty(filename))
{
// Create a new instance of the ChromePdfRenderer class.
var renderer = new ChromePdfRenderer();
// Render the file contents of the text box as a PDF document using the ChromePdfRenderer.
var pdfDocument = renderer.RenderHtmlAsPdf(pdfContent.Text);
// Save the PDF document to the specified file path using the SaveAs method.
pdfDocument.SaveAs(filename);
// Show a message box to indicate that the PDF file has been saved successfully.
MessageBox.Show("PDF has been saved Successfully!");
}
}
private void Save_Click(object sender, EventArgs e)
{
// Get the file path to save the PDF file.
string filename = getFilePath();
// If the file path is not empty or null, proceed with saving the PDF file.
if (!String.IsNullOrEmpty(filename))
{
// Create a new instance of the ChromePdfRenderer class.
var renderer = new ChromePdfRenderer();
// Render the file contents of the text box as a PDF document using the ChromePdfRenderer.
var pdfDocument = renderer.RenderHtmlAsPdf(pdfContent.Text);
// Save the PDF document to the specified file path using the SaveAs method.
pdfDocument.SaveAs(filename);
// Show a message box to indicate that the PDF file has been saved successfully.
MessageBox.Show("PDF has been saved Successfully!");
}
}
Private Sub Save_Click(ByVal sender As Object, ByVal e As EventArgs)
' Get the file path to save the PDF file.
Dim filename As String = getFilePath()
' If the file path is not empty or null, proceed with saving the PDF file.
If Not String.IsNullOrEmpty(filename) Then
' Create a new instance of the ChromePdfRenderer class.
Dim renderer = New ChromePdfRenderer()
' Render the file contents of the text box as a PDF document using the ChromePdfRenderer.
Dim pdfDocument = renderer.RenderHtmlAsPdf(pdfContent.Text)
' Save the PDF document to the specified file path using the SaveAs method.
pdfDocument.SaveAs(filename)
' Show a message box to indicate that the PDF file has been saved successfully.
MessageBox.Show("PDF has been saved Successfully!")
End If
End Sub
이 메서드의 단계별 설명은 다음과 같습니다:
- 메소드는 PDF 파일이 저장될 파일 경로를 얻기 위해
getFilePath메소드를 호출합니다. - 파일 경로가 빈 문자열이거나 null이 아닌 경우 메서드는 PDF 파일 저장을 계속 진행합니다.
- 메소드는
ChromePdfRenderer클래스의 새로운 인스턴스를 생성합니다. 이 라이브러리는 Google Chrome 브라우저 엔진을 사용하여 HTML 콘텐츠를 PDF 문서로 변환할 수 있는 방법을 제공합니다. - 그런 다음 메소드는
ChromePdfRenderer클래스의 RenderHtmlAsPdf 메소드를 사용하여 텍스트 박스pdfContent의 HTML 콘텐츠를 PDF 문서로 변환합니다. 이 PDF 문서는 PdfDocument 변수에 할당됩니다. - 메소드는
PdfDocument클래스의 SaveAs 메소드를 사용하여 지정된 파일 경로에 PDF 문서를 저장합니다. - 마지막으로 메서드는 PDF 파일이 성공적으로 저장되었음을 알리는 메시지 상자를 표시합니다.
getFilePath 메서드 (PDF 파일 저장)
이 메소드는 사용자에게 PDF 파일이 저장될 파일 경로를 선택하도록 SaveFileDialog을(를) 표시하는 데 사용됩니다.
public string getFilePath()
{
// Create a new instance of the SaveFileDialog class.
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
// Set the initial directory where the SaveFileDialog will open.
saveFileDialog1.InitialDirectory = @"D:\";
// Set the title of the SaveFileDialog.
saveFileDialog1.Title = "Save the PDF Files";
// Set the SaveFileDialog to check if the specified path exists.
saveFileDialog1.CheckPathExists = true;
// Set the default extension for the file type.
saveFileDialog1.DefaultExt = ".pdf";
// Set the filter to display only PDF files or all files.
saveFileDialog1.Filter = "PDF files (*.pdf)|*.pdf|All files (*.*)|*.*";
// Set the filter index to display the PDF filter as the default.
saveFileDialog1.FilterIndex = 2;
// Set the RestoreDirectory property to true so that the SaveFileDialog
// restores the current directory before closing.
saveFileDialog1.RestoreDirectory = true;
// Show the SaveFileDialog and get the result.
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
// If the user clicked the OK button in the SaveFileDialog, return the selected file path.
return saveFileDialog1.FileName;
}
// If the user did not click the OK button, return an empty string.
return String.Empty;
}
public string getFilePath()
{
// Create a new instance of the SaveFileDialog class.
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
// Set the initial directory where the SaveFileDialog will open.
saveFileDialog1.InitialDirectory = @"D:\";
// Set the title of the SaveFileDialog.
saveFileDialog1.Title = "Save the PDF Files";
// Set the SaveFileDialog to check if the specified path exists.
saveFileDialog1.CheckPathExists = true;
// Set the default extension for the file type.
saveFileDialog1.DefaultExt = ".pdf";
// Set the filter to display only PDF files or all files.
saveFileDialog1.Filter = "PDF files (*.pdf)|*.pdf|All files (*.*)|*.*";
// Set the filter index to display the PDF filter as the default.
saveFileDialog1.FilterIndex = 2;
// Set the RestoreDirectory property to true so that the SaveFileDialog
// restores the current directory before closing.
saveFileDialog1.RestoreDirectory = true;
// Show the SaveFileDialog and get the result.
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
// If the user clicked the OK button in the SaveFileDialog, return the selected file path.
return saveFileDialog1.FileName;
}
// If the user did not click the OK button, return an empty string.
return String.Empty;
}
Public Function getFilePath() As String
' Create a new instance of the SaveFileDialog class.
Dim saveFileDialog1 As New SaveFileDialog()
' Set the initial directory where the SaveFileDialog will open.
saveFileDialog1.InitialDirectory = "D:\"
' Set the title of the SaveFileDialog.
saveFileDialog1.Title = "Save the PDF Files"
' Set the SaveFileDialog to check if the specified path exists.
saveFileDialog1.CheckPathExists = True
' Set the default extension for the file type.
saveFileDialog1.DefaultExt = ".pdf"
' Set the filter to display only PDF files or all files.
saveFileDialog1.Filter = "PDF files (*.pdf)|*.pdf|All files (*.*)|*.*"
' Set the filter index to display the PDF filter as the default.
saveFileDialog1.FilterIndex = 2
' Set the RestoreDirectory property to true so that the SaveFileDialog
' restores the current directory before closing.
saveFileDialog1.RestoreDirectory = True
' Show the SaveFileDialog and get the result.
If saveFileDialog1.ShowDialog() = DialogResult.OK Then
' If the user clicked the OK button in the SaveFileDialog, return the selected file path.
Return saveFileDialog1.FileName
End If
' If the user did not click the OK button, return an empty string.
Return String.Empty
End Function
이 메서드의 단계별 설명은 다음과 같습니다:
- 메소드는
SaveFileDialog클래스의 새 인스턴스를 생성합니다. 이 클래스는 Windows Forms 라이브러리의 일부로, 사용자가 PDF 파일이 저장될 파일 경로를 선택할 수 있는 대화 상자를 제공합니다. - 메소드는
SaveFileDialog객체의 여러 속성을 설정하여 동작을 사용자 정의합니다.InitialDirectory속성은 대화 상자가 처음 열릴 디렉토리를 설정합니다.Title속성은 대화 상자의 제목을 설정합니다.CheckPathExists속성은 지정된 경로가 존재하는지 대화 상자가 확인해야 하는지를 지정합니다.DefaultExt속성은 파일 유형의 기본 파일 확장자를 설정합니다.Filter속성은 대화 상자에 표시되는 파일 유형 필터를 설정합니다.FilterIndex속성은 표시할 기본 필터를 설정합니다. 마지막으로,RestoreDirectory속성은 대화 상자가 닫히기 전에 현재 디렉토리를 복원할지를 지정합니다. - 메소드는
ShowDialog메소드를 호출하여SaveFileDialog을(를) 표시합니다. 이 메소드는 대화 상자를 표시하고 사용자가 '확인' 버튼을 클릭했는지 아니면 취소 버튼을 클릭했는지를 나타내는DialogResult값을 반환합니다. - 사용자가 '확인' 버튼을 클릭하면 메소드는
SaveFileDialog의FileName속성에 액세스하여 사용자가 선택한 파일 경로를 반환합니다. - 사용자가 "취소" 버튼을 클릭하거나 대화 상자를 닫으면 메서드는 빈 문자열을 반환합니다.
프로젝트를 실행하고 출력을 확인해 봅시다. 프로젝트를 실행하면 다음 양식이 열립니다.
Windows Forms 프로젝트 실행
아래에 표시된 것처럼 PDF 콘텐츠를 입력하고 "저장" 버튼을 클릭하십시오.
저장 대화 상자
생성된 PDF는 다음과 같습니다.
생성된 PDF 파일
IronPDF는 ChromePdfRenderer 클래스와 SaveFileDialog 대화 상자를 사용하여 HTML 콘텐츠를 PDF 문서로 변환하고 사용자가 선택한 파일 경로에 저장하는 간단한 방법을 제공합니다.
결론
Windows Forms 애플리케이션에서 PDF 파일을 저장하는 것은 일반적인 요구 사항이며, IronPDF는 이 작업을 수행하기 위한 사용하기 쉽고 유연한 방법을 제공합니다. 이 문서에서는 IronPDF를 사용하여 C# Windows Forms 애플리케이션에서 파일을 생성, 콘텐츠 추가 및 저장하는 방법을 보여줍니다. IronPDF를 사용하면 개발자가 코드 몇 줄만으로 애플리케이션에서 고품질의 PDF 파일을 생성할 수 있습니다.
IronPDF는 HTML을 PDF로 변환하는 튜토리얼, PDF 병합 예제 코드, PDF 페이지 분할 가이드, 텍스트 및 이미지 추출 방법 등 다양한 기능을 제공합니다. IronPDF는 개발용으로 무료이며, 상업적 프로젝트에서 사용할 수 있는 상업용 라이선스와 무료 체험판을 제공하여 개발자가 전용 지원 및 업데이트를 받으며 사용할 수 있습니다.
추가적으로, IronPDF는 Iron Suite의 일부로서, .NET 소프트웨어 구성 요소 번들에 라이브러리를 포함하고 있습니다:
- 바코드 생성 (IronBarcode),
- 엑셀 관리 (IronXL),
- 텍스트 추출 (IronOCR)
Iron Suite 전체를 구매하는 것은 두 가지 가격으로 다섯 가지 제품을 얻을 수 있는 경제적인 솔루션입니다.
자주 묻는 질문
C# Windows Forms 애플리케이션에서 PDF 파일을 어떻게 저장할 수 있나요?
IronPDF를 사용하여 C# Windows Forms 애플리케이션에서 PDF 파일을 저장할 수 있으며, 텍스트 상자와 버튼 같은 컨트롤을 양식에 설정하고 ChromePdfRenderer 클래스를 사용하여 콘텐츠를 PDF로 렌더링하고 저장하는 Save_Click 메서드를 구현하세요.
C#을 사용하여 PDF를 저장하기 위한 Windows Forms 애플리케이션 설정에 어떤 단계가 필요한가요?
PDF를 저장하기 위한 Windows Forms 애플리케이션을 설정하려면 Visual Studio에서 새 프로젝트를 생성하고, 레이블 및 리치 텍스트 상자와 같은 필요한 컨트롤을 추가하며, NuGet Package Manager를 통해 IronPDF를 설치하여 PDF 렌더링 기능을 활용하세요.
C#에서 HTML 콘텐츠를 PDF로 변환할 수 있는 방법은 무엇인가요?
IronPDF의 RenderHtmlAsPdf 메서드를 사용하여 C#에서 HTML 콘텐츠를 PDF로 변환할 수 있으며, 이를 통해 HTML 문자열을 직접 PDF 문서로 렌더링할 수 있습니다.
PDF 생성 맥락에서 Save_Click 메서드의 역할은 무엇인가요?
Save_Click 메서드는 애플리케이션 내에서 이벤트 핸들러로서 버튼의 클릭 이벤트를 캡처하여 IronPDF의 렌더링 클래스를 사용하여 텍스트 상자 내용을 PDF 파일로 렌더링하는 프로세스를 시작하는 역할을 합니다.
C# 애플리케이션에서 사용자가 PDF를 저장할 파일 경로를 선택하도록 어떻게 알릴 수 있나요?
C# 애플리케이션에서 SaveFileDialog 클래스를 사용하여 PDF를 저장할 파일 경로를 선택하도록 사용자에게 알릴 수 있으며, 파일 선택을 위한 인터페이스를 설정하고 렌더링된 PDF를 저장할 선택된 경로를 반환할 수 있습니다.
IronPDF는 PDF 조작을 위한 어떤 고급 기능을 제공하나요?
IronPDF는 HTML을 PDF로 변환, PDF 병합, PDF 페이지 나누기, 텍스트 및 이미지 추출과 같은 고급 기능을 제공하여 .NET 애플리케이션에서 PDF 조작에 대한 포괄적인 도구 세트를 제공합니다.
상업적 프로젝트에서 PDF 생성을 위해 IronPDF를 사용할 때 비용이 발생하나요?
IronPDF는 개발 목적으로는 체험 라이센스로 무료입니다. 그러나 상업적 프로젝트를 위해서는 상업용 라이센스가 필요하며, 전용 지원 및 정기 업데이트와 같은 혜택이 포함됩니다.
Iron Suite는 무엇이며 개발자에게 어떤 이점이 있나요?
Iron Suite는 바코드 생성, Excel 문서 조작 및 PDF 처리를 위한 도구들을 포함하는 .NET 라이브러리 모음입니다. 이것은 애플리케이션에 여러 가지 기능이 필요한 개발자들에게 비용 효율적인 솔루션을 제공합니다.
IronPDF는 .NET 10과 호환되며, 그것이 C#에서의 PDF 저장에 어떤 이점을 제공하나요?
네 — IronPDF는 데스크톱, 웹, 크로스플랫폼 프로젝트 유형을 포함한 .NET 10을 완벽히 지원합니다. .NET 10으로 빌드하면 더 빠른 런타임 성능, 최신 C# 강화 기능에 대한 접근 및 플랫폼 기능과의 더 긴밀한 통합과 같은 개선이 이루어지며, 이는 IronPDF의 RenderHtmlAsPdf 및 SaveAs 메서드를 통한 PDF 생성 및 저장을 보다 효율적으로 만듭니다.


