푸터 콘텐츠로 바로가기
IRONPDF 사용
IronPDF를 사용하여 프로그래밍 방식으로 PDF를 채우는 방법

Programmatically Fill PDF Forms in C# (Coding Tutorial)

This tutorial will demonstrate how to interact with forms in PDF files programmatically.

There are multiple .NET libraries out there on the market that allow us to fill PDF forms programmatically in C#. Some of them are difficult to understand, and some of them need to be paid for.

IronPDF is the best .NET Core library as it is easy to understand and free for development. Apart from filling PDF forms, IronPDF also allows creating new PDFs from HTML String, HTML files, and URLs.

Let's take a look at how to fill PDF forms programmatically using C#. First of all, a Console Application will be created for demonstration, but you can use any as per your requirement.

Create a Visual Studio Project

Open Microsoft Visual Studio. Click on Create New Project > Select Console Application from templates > Press Next > Name your Project. Press Next > Select Target Framework. Click the Create button. The project will be created as shown below.

Programmatically Fill PDF Forms in C# (Coding Tutorial), Figure 1: a newly created Console Application in Visual Studio a newly created Console Application in Visual Studio

Install the IronPDF Library

As discussed before, the IronPDF library will be used in this tutorial. The main reason for using this .NET library is that it is free for development and provides all features in a single library.

Go to the Package Manager Console. Type the following command:

Install-Package IronPdf

This command will install the IronPDF library for us. Next, let's begin the coding.

Read PDF Documents

The first step to filling out a PDF form is reading the PDF document. Obviously, how could we fill out the form without reading it first? The following PDF document will be used for the demonstration. You can download it from the Google Drive Link, or you may use your document.

Programmatically Fill PDF Forms in C# (Coding Tutorial), Figure 2: The sample PDF file to fill out form The sample PDF file to fill out form

The code to read this file is:

using IronPdf;

// Load the PDF document from the file path
PdfDocument doc = PdfDocument.FromFile(@"D:\myPdfForm.pdf");
using IronPdf;

// Load the PDF document from the file path
PdfDocument doc = PdfDocument.FromFile(@"D:\myPdfForm.pdf");
$vbLabelText   $csharpLabel

Pass the complete path of the PDF document inside the FromFile method. This will read the PDF file from your local system.

Get PDF Forms

Write the following line of code to get the form from the loaded PDF document.

var form = doc.Form;
var form = doc.Form;
$vbLabelText   $csharpLabel

Get Form Fields

To get the form fields to set their value, IronPDF makes this very easy by accessing the form fields using two methods: either by field name or via the index. Let's discuss both one by one.

Get form Field by Name

The following code will get the field by name:

// Retrieve the form field using its name
var field = form.FindFormField("First Name");
// Retrieve the form field using its name
var field = form.FindFormField("First Name");
$vbLabelText   $csharpLabel

The FindFormField method takes the field name as the argument. This is fault-tolerant and will attempt to match case mistakes and partial field names.

Get Form Field by Index

We can also get PDF form fields by using the index. The index starts from zero. The following sample code is used to get form fields by index.

// Retrieve the form field using its index
var field = form.Fields[0];
// Retrieve the form field using its index
var field = form.Fields[0];
$vbLabelText   $csharpLabel

Fill PDF Forms

Next, let's combine all the code to fill out the PDF form.

using IronPdf;

class Program
{
    static void Main()
    {
        // Load the PDF document from the file path
        PdfDocument doc = PdfDocument.FromFile(@"D:\myPdfForm.pdf");

        // Access the PDF form
        var form = doc.Form;

        // Fill out the form fields using their index
        form.Fields[0].Value = "John";
        form.Fields[1].Value = "Smith";
        form.Fields[2].Value = "+19159969739";
        form.Fields[3].Value = "John@email.com";
        form.Fields[4].Value = "Chicago";

        // Save the modified PDF document
        doc.SaveAs(@"D:\myPdfForm.pdf");
    }
}
using IronPdf;

class Program
{
    static void Main()
    {
        // Load the PDF document from the file path
        PdfDocument doc = PdfDocument.FromFile(@"D:\myPdfForm.pdf");

        // Access the PDF form
        var form = doc.Form;

        // Fill out the form fields using their index
        form.Fields[0].Value = "John";
        form.Fields[1].Value = "Smith";
        form.Fields[2].Value = "+19159969739";
        form.Fields[3].Value = "John@email.com";
        form.Fields[4].Value = "Chicago";

        // Save the modified PDF document
        doc.SaveAs(@"D:\myPdfForm.pdf");
    }
}
$vbLabelText   $csharpLabel

The sample code above will fill the form fields by index values. You can also do the same using the field names mentioned earlier. Let's run the program to see the output.

Filled PDF Form

Programmatically Fill PDF Forms in C# (Coding Tutorial), Figure 3: The filled form in the sample PDF file

You can see that the library can fill the PDF form with the simplest code, without any need for complex logic. This is the reason IronPDF is recommended.

Let's suppose you do not yet have any PDF documents with forms — don't worry, IronPDF provides full support to generate PDF forms. Follow the steps below:

Generate a new PDF form document

Create A New HTML File

Create a new HTML file and paste the following code:

<!DOCTYPE html>
<html>
<body>

<h2>PDF Forms</h2>

<form action="/action_page.php">
  <label for="fname">First name:</label><br>
  <input type="text" id="fname" name="fname"><br>
  <label for="lname">Last name:</label><br>
  <input type="text" id="lname" name="lname"><br>
  <label for="contact">Contact #:</label><br>
  <input type="text" id="contact" name="contact"><br>
  <label for="email">Email:</label><br>
  <input type="text" id="email" name="email"><br>
  <label for="city">City:</label><br>
  <input type="text" id="city" name="city"><br>
</form> 

</body>
</html>
<!DOCTYPE html>
<html>
<body>

<h2>PDF Forms</h2>

<form action="/action_page.php">
  <label for="fname">First name:</label><br>
  <input type="text" id="fname" name="fname"><br>
  <label for="lname">Last name:</label><br>
  <input type="text" id="lname" name="lname"><br>
  <label for="contact">Contact #:</label><br>
  <input type="text" id="contact" name="contact"><br>
  <label for="email">Email:</label><br>
  <input type="text" id="email" name="email"><br>
  <label for="city">City:</label><br>
  <input type="text" id="city" name="city"><br>
</form> 

</body>
</html>
HTML

Save this example HTML File. You can customize this HTML as per your form requirement.

Next, write the following code in your C# Program.

using IronPdf;

class Program
{
    static void Main()
    {
        // Create an instance of ChromePdfRenderer
        var renderer = new ChromePdfRenderer();

        // Render the HTML file as a PDF
        var pdfDocument = renderer.RenderHtmlFileAsPdf(@"D:\myForm.html");

        // Save the PDF document to the specified file path
        pdfDocument.SaveAs(@"D:\myForm.pdf");
    }
}
using IronPdf;

class Program
{
    static void Main()
    {
        // Create an instance of ChromePdfRenderer
        var renderer = new ChromePdfRenderer();

        // Render the HTML file as a PDF
        var pdfDocument = renderer.RenderHtmlFileAsPdf(@"D:\myForm.html");

        // Save the PDF document to the specified file path
        pdfDocument.SaveAs(@"D:\myForm.pdf");
    }
}
$vbLabelText   $csharpLabel

Run the program to see the resulting PDF forms document.

Programmatically Fill PDF Forms in C# (Coding Tutorial), Figure 3: The PDF form generated from an HTML file The PDF form that generated from an HTML file

Summary

It is important to automatically and programmatically fill out PDF forms. In this article, the easiest approach is suggested for filling PDF forms in C# using IronPDF. Additionally, you also learned how to generate new PDF forms from scratch.

Additionally, IronPDF also offers developers methods to extract text and content from a PDF, render charts in PDFs, insert barcodes, enhance security with passwords and watermark programmatically.

There are other many useful libraries such as IronBarcode for working with barcodes, IronXL for working with Excel documents, and IronOCR for working with OCR. You can get all five libraries for the price of just two by purchasing the complete Iron Suite. Please visit the Iron Software Licensing Page for more details.

자주 묻는 질문

C#을 사용하여 PDF 양식을 프로그래밍 방식으로 채우려면 어떻게 해야 하나요?

IronPDF를 사용하면 PdfDocument.FromFile로 문서를 로드하고 doc.Form.Fields를 사용하여 양식 필드에 액세스하여 값을 설정함으로써 C#에서 PDF 양식을 프로그래밍 방식으로 채울 수 있습니다.

PDF 양식을 채우기 위해 C# 프로젝트를 설정하려면 어떤 단계를 거쳐야 하나요?

먼저 Visual Studio에서 콘솔 애플리케이션을 만듭니다. 그런 다음 패키지 관리자 콘솔에서 Install-Package IronPdf를 사용하여 IronPDF를 설치합니다. PdfDocument.FromFile를 사용하여 PDF를 로드하고 필요에 따라 양식 필드를 조작합니다.

IronPDF를 사용하여 C#의 HTML에서 새로운 PDF 양식을 생성할 수 있나요?

예, IronPDF는 ChromePdfRenderer 클래스를 사용하여 HTML 양식을 PDF 문서로 렌더링하여 새로운 PDF 양식을 생성할 수 있습니다. 이를 통해 웹 양식 입력을 기반으로 동적 PDF를 생성할 수 있습니다.

.NET 애플리케이션에서 PDF 양식 처리를 위해 IronPDF를 사용하면 어떤 주요 이점이 있나요?

IronPDF는 .NET 애플리케이션에서 PDF 양식 처리를 통합하기 위한 사용자 친화적인 접근 방식을 제공합니다. 간편한 통합과 무료 개발 기능으로 양식 채우기, 텍스트 추출 및 문서 보안을 지원합니다.

IronPDF를 사용하여 PDF 양식에서 텍스트를 추출하려면 어떻게 해야 하나요?

IronPDF는 PDF 양식에서 텍스트를 추출하는 방법을 제공합니다. PdfDocument.FromFile로 문서를 로드한 후 pdfDocument.ExtractAllText()와 같은 메서드를 사용하여 텍스트 콘텐츠에 액세스하고 추출할 수 있습니다.

.NET 라이브러리를 사용하여 PDF 문서의 보안을 보장할 수 있나요?

예, IronPDF는 PDF 문서의 민감한 정보를 보호하기 위한 디지털 서명, 리댁션, 암호화 등 PDF 보안을 강화하는 기능을 제공합니다.

PDF 양식 필드가 예상대로 업데이트되지 않는 경우 어떤 문제 해결 단계를 수행해야 하나요?

양식 필드가 IronPDF를 사용하여 올바르게 식별되고 액세스되는지 확인합니다. 필드 이름 또는 인덱스를 확인하고 doc.Form.FindFormField('FieldName').Value = '새 값'를 사용하여 필드 값을 업데이트합니다.

C#에서 양식 필드를 채운 후 수정된 PDF 문서를 저장하려면 어떻게 해야 하나요?

IronPDF를 사용하여 양식 필드를 수정한 후 업데이트된 문서를 pdfDocument.SaveAs('경로/to/newfile.pdf')로 저장하여 변경 사항을 유지하세요.

IronPDF는 PDF 양식 처리 외에 다른 문서 작업도 처리할 수 있나요?

예, IronPDF는 텍스트 추출, 차트 렌더링, 문서 보안 강화 등 다양한 PDF 작업을 처리할 수 있어 PDF 관리를 위한 종합적인 도구입니다.

PDF 양식으로 작업하는 개발자에게 IronPDF가 어떻게 도움이 될 수 있나요?

IronPDF는 PDF 양식을 채우고 조작할 수 있는 간단한 API를 제공하여 HTML-PDF 렌더링 및 .NET 애플리케이션과의 통합과 같은 기능을 제공함으로써 개발자의 생산성을 향상시킵니다.

IronPDF는 .NET 10을 지원하며, IronPDF를 사용하여 C#에서 PDF 양식을 채운다는 것은 무엇을 의미하나요?

예, IronPDF는 .NET 8 및 .NET 9를 포함한 최신 .NET 버전을 지원하며, 곧 출시될 .NET 10 릴리스(2025년 11월 예정)와 이미 호환됩니다. 즉, .NET 10에서 완벽한 호환성을 갖춘 C#에서 양식 채우기 및 PDF 조작을 위해 IronPDF를 계속 사용할 수 있습니다.

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

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

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