푸터 콘텐츠로 바로가기
IRONPDF 사용

How to Save PDF File in C# (Beginner Tutorial)

This article will explore how to use IronPDF to save PDF files from a Windows Forms Application or any .NET Application.

The IronPDF Library is a .NET library that provides easy-to-use classes and methods for generating and working with PDF files in C# applications. It allows developers to create, modify, and save PDF files with just a few lines of code, making it an excellent choice for Windows Forms Applications.

Step 1: Create a New Windows Forms application

First, create a new Visual Studio Project. Here are the steps to create a new C# Windows Forms Application in Visual Studio 2022

  1. Open Visual Studio 2022 as shown below.

    How to Save PDF File in C# (Beginner Tutorial), Figure 1: Visual Studio 2022 Visual Studio 2022

  2. Click on "Create a new project" on the start page or go to "File" > "New" > "Project".
  3. In the "Create a new project" dialog box, select "Windows Forms App" or "Windows Forms App (.NET Framework)" under "Create a new project" as shown below.

    How to Save PDF File in C# (Beginner Tutorial), Figure 2: New Forms App New Forms App

  4. Enter a name for your project and choose a location to save it to.

    How to Save PDF File in C# (Beginner Tutorial), Figure 3: Project location Project location

  5. Choose .NET Framework. Select .NET 7.0 from the drop-down menu.
  6. Click on the Create button.

    How to Save PDF File in C# (Beginner Tutorial), Figure 4: Additional Information Additional Information

  7. Visual Studio will create a new C# Windows Forms Application project for you, with a default form named "Form1" added to the project as shown below.

    How to Save PDF File in C# (Beginner Tutorial), Figure 5: Form1 project Form1 project

That's it! Now we will start building the Windows Forms Application using the designer, adding controls and functionality for creating and saving a PDF document file.

Step 2: Design the Form

You can design the form as per your preferences. This tutorial will make a minimalistic design by adding two labels, one rich text box, and two buttons.

How to Save PDF File in C# (Beginner Tutorial), Figure 6: Adding buttons to form Adding buttons to form

Step 3: Install IronPDF

The next step is to install IronPDF in this project to use its rich functionalities.

IronPDF can be installed using NuGet Package Manager in Visual Studio. You can navigate to the NuGet Package Manager Console by going to Tools > NuGet Package Manager > Package Manager Console.

Type the following command and press Enter:

Install-Package IronPdf

This command will download and install the IronPDF package in your project. Once installed, we can start using IronPDF.

Write Code to Create and Save PDF File

To start with the flow, write two methods: Save_Click and getFilePath in the Form1.cs class. These methods are used together to save the content of a text box as a PDF file using the ChromePdfRenderer Class library. Let's go through each method to understand how it works.

Save_Click Method (Create PDF Document)

The following method is an event handler for a button-click event. The purpose of this method is to save the content of a text box as a PDF file.

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!");
    }
}
$vbLabelText   $csharpLabel

Here's a step-by-step breakdown of what this method does:

  1. The method calls the getFilePath method to get the file path where the PDF file will be saved.
  2. If the file path is not empty or null, the method proceeds with saving the PDF file.
  3. The method creates a new instance of the ChromePdfRenderer class. This is a library that provides a way to convert HTML content into PDF documents using the Google Chrome browser engine.
  4. The method then uses the RenderHtmlAsPdf Method of the ChromePdfRenderer class to convert the HTML content of the text box pdfContent into a PDF document. This PDF document is assigned to the PdfDocument Variable.
  5. The method saves the PDF document to the specified file path using the SaveAs Method of the PdfDocument class.
  6. Finally, the method shows a message box to indicate that the PDF file has been saved successfully.

getFilePath Method (Save PDF Files)

This method is used to display a SaveFileDialog to the user to select a file path where the PDF file will be saved.

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;
}
$vbLabelText   $csharpLabel

Here's a step-by-step breakdown of what this method does:

  1. The method creates a new instance of the SaveFileDialog class. This class is part of the Windows Forms library and provides a dialog box that allows the user to select a file path where the PDF file will be saved.
  2. The method sets several properties of the SaveFileDialog object to customize its behavior. The InitialDirectory property sets the directory where the dialog box will first open. The Title property sets the title of the dialog box. The CheckPathExists property specifies whether the dialog box should check if the specified path exists. The DefaultExt property sets the default file extension for the file type. The Filter property sets the file type filters that are displayed in the dialog box. The FilterIndex property sets the default filter to display. Finally, the RestoreDirectory property specifies whether the dialog box should restore the current directory before closing.
  3. The method shows the SaveFileDialog by calling its ShowDialog method. This method displays the dialog box and returns a DialogResult value that indicates whether the user clicked the "OK" button or the Cancel button.
  4. If the user clicks the "OK" button, the method returns the file path that the user selected by accessing the FileName property of the SaveFileDialog.
  5. If the user clicks the "Cancel" button or closes the dialog box, the method returns an empty string.

Let's run the project and see the output. Run the project, and the following form will open.

How to Save PDF File in C# (Beginner Tutorial), Figure 7: Running Windows Forms project Running Windows Forms project

Enter your PDF content and click on the "Save" button as shown below.

How to Save PDF File in C# (Beginner Tutorial), Figure 8: Save dialog box Save dialog box

The following PDF is created.

How to Save PDF File in C# (Beginner Tutorial), Figure 9: Created PDF file Created PDF file

IronPDF provides a simple way to convert HTML content into PDF documents and save them to a user-selected file path using the ChromePdfRenderer class and the SaveFileDialog dialog box.

Conclusion

Saving PDF files from a Windows Forms Application is a common requirement, and IronPDF provides an easy-to-use and flexible method to accomplish this task. This article demonstrated how to use IronPDF to create, add content, and save files in a C# Windows Forms Application. With IronPDF, developers can generate high-quality PDF files from their applications with just a few lines of code.

IronPDF offers a range of features such as HTML to PDF Conversion Tutorial, PDF Merging Example Code, Splitting PDF Pages Guide, and Extracting Text and Images How-to, and more. IronPDF is free for development and available under a Commercial License with a Free Trial, which allows developers to use it in commercial projects and includes dedicated support and updates.

Additionally, IronPDF is part of the Iron Suite, which is a bundle of .NET software components that includes libraries for:

Purchasing the complete Iron Suite is a cost-effective solution as you can get all five products for the price of two.

자주 묻는 질문

C# Windows Forms 애플리케이션에 PDF 파일을 저장하려면 어떻게 해야 하나요?

텍스트 상자 및 버튼과 같은 컨트롤이 있는 양식을 설정하고 Save_Click 메서드를 구현하여 ChromePdfRenderer 클래스를 사용하여 콘텐츠를 렌더링하고 PDF로 저장하는 방식으로 IronPDF를 사용하여 C# Windows Forms 애플리케이션에 PDF 파일을 저장할 수 있습니다.

C#을 사용하여 PDF를 저장하도록 Windows Forms 애플리케이션을 설정하려면 어떤 단계를 거쳐야 하나요?

PDF 저장을 위한 Windows Forms 애플리케이션을 설정하려면 Visual Studio에서 새 프로젝트를 만들고, 레이블과 서식 있는 텍스트 상자 등 필요한 컨트롤을 추가하고, NuGet 패키지 관리자를 통해 IronPDF를 설치하여 PDF 렌더링 기능을 활용하세요.

C#에서 HTML 콘텐츠를 PDF로 변환하려면 어떻게 해야 하나요?

HTML 문자열을 가져와 PDF 문서로 직접 렌더링할 수 있는 IronPDF의 RenderHtmlAsPdf 메서드를 사용하여 C#에서 HTML 콘텐츠를 PDF로 변환할 수 있습니다.

PDF 생성의 맥락에서 Save_Click 메서드의 역할은 무엇인가요?

Save_Click 메서드는 애플리케이션 내에서 이벤트 핸들러 역할을 하며, 버튼 클릭 이벤트를 캡처하여 IronPDF의 렌더링 클래스를 사용하여 텍스트 상자 콘텐츠를 PDF 파일로 렌더링하는 프로세스를 시작합니다.

C# 애플리케이션에서 PDF를 저장할 파일 경로를 선택하라는 메시지를 사용자에게 표시하려면 어떻게 해야 하나요?

C# 애플리케이션에서는 파일 선택 인터페이스를 설정하고 렌더링된 PDF를 저장하기 위해 선택한 경로를 반환할 수 있는 SaveFileDialog 클래스를 사용하여 사용자에게 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의 RenderHtmlAsPdfSaveAs 메서드를 통한 PDF 생성 및 저장이 더 효율적으로 이루어집니다.

커티스 차우
기술 문서 작성자

커티스 차우는 칼턴 대학교에서 컴퓨터 과학 학사 학위를 취득했으며, Node.js, TypeScript, JavaScript, React를 전문으로 하는 프론트엔드 개발자입니다. 직관적이고 미적으로 뛰어난 사용자 인터페이스를 만드는 데 열정을 가진 그는 최신 프레임워크를 활용하고, 잘 구성되고 시각적으로 매력적인 매뉴얼을 제작하는 것을 즐깁니다.

커티스는 개발 분야 외에도 사물 인터넷(IoT)에 깊은 관심을 가지고 있으며, 하드웨어와 소프트웨어를 통합하는 혁신적인 방법을 연구합니다. 여가 시간에는 게임을 즐기거나 디스코드 봇을 만들면서 기술에 대한 애정과 창의성을 결합합니다.