푸터 콘텐츠로 바로가기
IRONPDF 사용
C#에서 텍스트를 PDF로 변환하는 방법

C# Text to PDF (Code Example Tutorial)

Over the past few years, the use of .NET Technology has increased rapidly, especially following the release of .NET Core, which ultimately increased the use of the C# programming language. It is therefore now essential that any C# programmer learns how to convert text into PDF files.

There are multiple use cases where it is needed to convert text into PDFs.

  1. Making Reports
  2. Converting Invoices into PDF
  3. Making a Text Editor
  4. Creating Fillable PDF Forms
  5. Converting text files into PDF files

...and many more.

It is necessary to have a third-party library to convert text into PDF documents. There are multiple options on the market, but some are paid, some are difficult to use, and some have performance issues. There is a library that is free for development and easy to use, so much so that all it takes is just one line of code to convert text into PDF. It also provides higher performance levels. This library is IronPDF.

IronPDF is supported by all .NET Frameworks. It is developer-friendly and provides a variety of features in a single library, including creating PDFs from URLs, creating PDFs from text, converting HTML files to PDF files, and many more.

Let's take a look at an example of how to convert text to PDF.

Create a Visual Studio Project

Open Microsoft Visual Studio. Click on Create New Project. Select the template "Console Application" for simplicity, but you can use Windows Forms, ASP.NET Web Forms, MVC, Web APIs, or any template as per your needs.

Select Next, Name the Project, Select Target Framework, and press Create. A new console project will be created.

C# Text to PDF (Code Example Tutorial), Figure 1: Create a new Console Application in Visual Studio Create a new Console Application in Visual Studio

Next, install the NuGet Package for IronPDF.

IronPDF is a .NET library for generating, reading, editing, and saving PDF files in .NET projects. IronPDF features HTML-to-PDF for .NET 5 Core, Standard, and Framework, with full HTML-to-PDF support including CSS3 and JS.

Install the NuGet Package

To install the IronPDF NuGet Package, go to Tools > NuGet Package Manager > Package Manager Console. The following window will appear:

C# Text to PDF (Code Example Tutorial), Figure 2: Package Manager Console Package Manager Console

Next, write the following command in the Package Manager Console.

Install-Package IronPdf

Press Enter.

C# Text to PDF (Code Example Tutorial), Figure 3: Installation progress in the Package Manager Console Installation progress in the Package Manager Console

This will install the IronPDF library to be able to use all the functionalities provided by this library anywhere in the project.

Convert Text to PDF

Next, let's address the main task here --- converting C# text into a PDF file.

Firstly, reference the IronPDF library in the program.cs file. Write the following code snippet at the top of the file.

using IronPdf;
using IronPdf;
$vbLabelText   $csharpLabel

Next, write the following code inside the main function. This code will convert text to PDF.

// Create an instance of ChromePdfRenderer, which is responsible for rendering HTML into PDF
ChromePdfRenderer renderer = new ChromePdfRenderer();

// Render a simple HTML string as a PDF document
PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>This is my PDF</h1><p>This is generated for the tutorial of C# txt to PDF</p>");

// Save the generated PDF document to a specified path
pdf.SaveAs(@"D:\Iron Software\textToPDF\myFirstPDF.pdf");
// Create an instance of ChromePdfRenderer, which is responsible for rendering HTML into PDF
ChromePdfRenderer renderer = new ChromePdfRenderer();

// Render a simple HTML string as a PDF document
PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>This is my PDF</h1><p>This is generated for the tutorial of C# txt to PDF</p>");

// Save the generated PDF document to a specified path
pdf.SaveAs(@"D:\Iron Software\textToPDF\myFirstPDF.pdf");
$vbLabelText   $csharpLabel

Code Explanation

Firstly, create the object of the ChromePdfRenderer. This object is responsible for converting text to PDF. In the second line, the RenderHtmlAsPdf function is called with the reference of the renderer object.

This will generate a PDF from the text passed in the argument of this function. That PDF will then be temporarily stored as a PDF Document type.

Finally, the newly generated PDF file is saved to the local drive using the SaveAs function. Pass the path as an argument in the SaveAs function.

Output

This is the output of the above code. It is very easy to generate PDF programmatically from text.

C# Text to PDF (Code Example Tutorial), Figure 4: The output PDF file from the code sample The output PDF file from the code sample

TXT File to PDF file

In the above example, it shows how to convert simple TXT to PDF. Now, this example will demonstrate how to convert a text document into a PDF document.

Given a sample source TXT file as shown below.

C# Text to PDF (Code Example Tutorial), Figure 5: The sample TXT file The sample TXT file

The following code will convert a text file to PDF.

First, add the following namespace:

using System.IO;
using System.IO;
$vbLabelText   $csharpLabel

Write the following code snippet inside the main function.

// Read all text from a TXT file into a string
string text = File.ReadAllText(@"D:\Iron Software\textToPDF\myTxtFile.txt");

// Use the ChromePdfRenderer to render the text as a PDF document
ChromePdfRenderer renderer = new ChromePdfRenderer();
PdfDocument pdf = renderer.RenderHtmlAsPdf(text);

// Save the resulting PDF file to a specified location
pdf.SaveAs(@"D:\Iron Software\textToPDF\textFileToPDF.pdf");
// Read all text from a TXT file into a string
string text = File.ReadAllText(@"D:\Iron Software\textToPDF\myTxtFile.txt");

// Use the ChromePdfRenderer to render the text as a PDF document
ChromePdfRenderer renderer = new ChromePdfRenderer();
PdfDocument pdf = renderer.RenderHtmlAsPdf(text);

// Save the resulting PDF file to a specified location
pdf.SaveAs(@"D:\Iron Software\textToPDF\textFileToPDF.pdf");
$vbLabelText   $csharpLabel

File.ReadAllText will read all the text from the file specified in the argument of the function. This text is then held in a string variable.

This variable is then passed as an argument of the RenderHtmlAsPdf function. This function will convert text into a PDF document.

Finally, specify the output filename in the SaveAs function.

Output

C# Text to PDF (Code Example Tutorial), Figure 6: The output PDF file from a TXT file The output PDF file from a TXT file

In the above example, it is very easy to convert text into a new PDF document.

Add Watermark

Let's add a watermark to this newly created PDF. Watermarks can help to avoid the misuse of documents. You can set your watermark as per your needs. Let's consider the following example:

// Apply a watermark to the PDF with specified text and layout properties
pdf.ApplyWatermark("<h1>my Watermark</h1>", 45, 45, IronPdf.Editing.VerticalAlignment.Top, IronPdf.Editing.HorizontalAlignment.Center);

// Save the PDF with the watermark applied
pdf.SaveAs(@"D:\Iron Software\textToPDF\myFirstPDF.pdf");
// Apply a watermark to the PDF with specified text and layout properties
pdf.ApplyWatermark("<h1>my Watermark</h1>", 45, 45, IronPdf.Editing.VerticalAlignment.Top, IronPdf.Editing.HorizontalAlignment.Center);

// Save the PDF with the watermark applied
pdf.SaveAs(@"D:\Iron Software\textToPDF\myFirstPDF.pdf");
$vbLabelText   $csharpLabel

The pdf variable holds a PdfDocument type. The ApplyWatermark function will add a watermark to the document. Pass your watermark text as an argument of the function such as "my watermark" as an example. The second argument is the watermark's rotation angle. The third and fourth arguments specify the vertical and horizontal alignment of the watermark.

Output

The following is the output generated by the sample code:

C# Text to PDF (Code Example Tutorial), Figure 7: The PDF file with the watermark in the center The PDF file with the watermark in the center

Print a PDF Document

Printing a PDF document using IronPDF is very easy --- just write the following line of code:

// Print the PDF document to the default printer
pdf.Print();
// Print the PDF document to the default printer
pdf.Print();
$vbLabelText   $csharpLabel

This will print a PDF document on your default printer. There are multiple printer settings available, and you can choose as per your requirements. For more details regarding PDF print settings, please refer to this PDF Printing Guide.

Summary

This tutorial showed a very easy way to convert text into a PDF file with step-by-step examples and code explanations: convert text to PDF, generate a PDF from a TXT file, and print this PDF file. Moreover, it covered how to add watermarks to the documents.

There are multiple useful and interesting features provided by IronPDF such as rendering charts in PDFs, adding barcodes, enhancing security with passwords, and even handling PDF forms, but it is impossible to cover them all here. For more details, please visit the IronPDF Feature Overview.

IronPDF is a part of the Iron Software Suite. The suite includes an array of interesting products including IronXL, IronBarcode, IronOCR, and IronWebScraper. It is assured that you will find all of these products helpful. You can save up to 250% by purchasing the complete Iron Suite, as you can currently get all five products for the price of just two. For more details, please check the Iron Software Suite Pricing.

Extracting Text with IronOCR into Searchable PDFs

Csharp Text To Pdf 10 related to Extracting Text with IronOCR into Searchable PDFs

Another method for creating PDF documents from provided text would be to make use of the IronOCR library to extract text from scanned documents and images, and then use the extracted content to create a new PDF document. So why do this instead of simply using the scanned document?

Scanned documents are not easy to modify or search, as they are still just images, only with text instead of pictures. So how would you create searchable PDFs, what exactly is IronOCR, and how could we make it work with IronPDF? Let’s take a look at how each of these questions can be answered.

IronOCR: What is it?

IronOCR is a powerful .NET library that lets developers like yourself perform OCR tasks with ease on provided images, scanned documents, and even specialized formats such as passports and license plates. In addition to powerful OCR capabilities, IronOCR also provides the tools to refine your images if they need to be edited in order to be easier scanned. These editing tools include the DeNoise(), Sharpen() and Deskew(), to name a few.

Extracting Text with IronOCR

Now, let’s take a look at how you can extract text from scanned documents and turn it into a searchable PDF that can then be used and edited by IronPDF. First, we’ll take a scanned document, like the one below, and load it into our code.

Csharp Text To Pdf 8 related to Extracting Text with IronOCR

using IronOcr;

class Program
{
    static void Main(string[] args)
    {

        // Create an instance of the OCR Tesseract
        var ocr = new IronTesseract();

        // Enable searchable PDF output
        ocr.Configuration.RenderSearchablePdf = true;

        // Load a scanned document image
        using var input = new OcrInput();
        input.LoadImage("sample-page.png");

        // Perform OCR on the scanned document
        OcrResult result = ocr.Read(input);

        // Output the recognized text
        Console.WriteLine(result.Text);

        // Save the recognized text to a file
        result.SaveAsSearchablePdf("output.pdf");
    }
}
using IronOcr;

class Program
{
    static void Main(string[] args)
    {

        // Create an instance of the OCR Tesseract
        var ocr = new IronTesseract();

        // Enable searchable PDF output
        ocr.Configuration.RenderSearchablePdf = true;

        // Load a scanned document image
        using var input = new OcrInput();
        input.LoadImage("sample-page.png");

        // Perform OCR on the scanned document
        OcrResult result = ocr.Read(input);

        // Output the recognized text
        Console.WriteLine(result.Text);

        // Save the recognized text to a file
        result.SaveAsSearchablePdf("output.pdf");
    }
}
$vbLabelText   $csharpLabel

Output

Csharp Text To Pdf 9 related to Output

This creates a PDF document that maintains the original scanned document’s layout and styling, only now it is a searchable, easy-to-edit PDF document that can be used by IronPDF for further manipulation or sharing.

IronPDF and IronOCR Licensing

When working with powerful .NET libraries like IronPDF and IronOCR, developers often want clarity on how licensing works—especially in production environments. Both libraries follow IronSoftware’s straightforward licensing model, designed to support projects ranging from small prototypes to large-scale enterprise solutions.

IronPDF Licensing

IronPDF is licensed per developer with flexible deployment rights, meaning a single developer license covers unlimited usage across applications and servers. This makes it a cost-effective choice for teams that need to scale. Licenses are perpetual, so once purchased, they can be used indefinitely. Subscription options are also available for those who prefer annual renewals with updates and priority support included.

Want to try before you buy? Try the IronPDF free trial to test out its robust set of features for yourself.

IronOCR Licensing

IronOCR follows the same simple licensing model as IronPDF, offering per-developer licenses with unlimited deployment rights. This makes it especially appealing for projects that require scalable OCR functionality, such as document digitization, automated text extraction, or searchable PDF generation.

With IronOCR, licensing covers the entire suite of features, including support for 125+ languages, PDF text recognition, and advanced image-to-text conversions. Just like IronPDF, you can deploy to cloud services, containers, or enterprise servers without additional fees.

Just like IronPDF, IronOCR also offers a free trial for developers looking to try it out for themselves before purchasing a licence.

Why This Matters for Developers

Many competing PDF and OCR solutions add complexity with runtime licensing, per-server fees, or feature-based tiers. Iron Software keeps it simple: one developer license unlocks the full power of the library across all your projects. This lets you focus on coding and delivering features—not tracking usage limits or negotiating enterprise contracts.

자주 묻는 질문

C#에서 텍스트를 PDF로 변환하려면 어떻게 해야 하나요?

IronPDF 라이브러리를 사용하여 C#에서 텍스트를 PDF로 변환할 수 있습니다. NuGet 패키지 관리자를 통해 IronPDF를 설치한 다음 ChromePdfRenderer 클래스를 사용하여 HTML 또는 일반 텍스트를 PDF 문서로 렌더링한 다음 SaveAs 메서드를 사용하여 저장합니다.

이 방법을 사용하여 텍스트를 PDF로 변환하면 어떤 이점이 있나요?

IronPDF를 사용하여 텍스트를 PDF로 변환하면 여러 .NET 프레임워크를 지원하여 고성능과 사용 편의성을 제공합니다. 몇 줄의 코드만으로 변환 프로세스를 간소화하여 보고서, 송장 및 채울 수 있는 양식을 만드는 데 이상적입니다.

C#으로 PDF에 워터마크를 추가하려면 어떻게 해야 하나요?

C#에서 PDF에 워터마크를 추가하려면 PdfDocument 객체에서 IronPDF의 ApplyWatermark 메서드를 사용합니다. 필요에 따라 워터마크의 텍스트, 회전 및 정렬을 사용자 지정할 수 있습니다.

C#을 사용하여 PDF 문서를 인쇄할 수 있나요?

예, IronPDF를 사용하면 문서를 기본 프린터로 전송하는 PdfDocument 객체에서 Print 메서드를 호출하여 PDF 문서를 인쇄할 수 있습니다.

C#에서 TXT 파일을 PDF로 변환하려면 어떻게 해야 하나요?

C#에서 TXT 파일을 PDF로 변환하려면 File.ReadAllText를 사용하여 파일에서 텍스트를 읽고 IronPDF의 ChromePdfRenderer를 사용하여 이 텍스트를 PDF 형식으로 렌더링합니다. 마지막으로 SaveAs 메서드를 사용하여 PDF를 저장합니다.

이 라이브러리를 사용하여 어떤 다른 파일 변환을 수행할 수 있나요?

IronPDF는 텍스트에서 PDF로의 변환뿐만 아니라 차트 렌더링, 바코드 추가, 비밀번호로 문서 보안, PDF 양식 처리 등 다양한 기능을 처리할 수 있습니다.

프로젝트에 IronPDF 라이브러리를 설치하려면 어떻게 해야 하나요?

Visual Studio 프로젝트에 IronPDF를 설치하려면 패키지 관리자 콘솔을 열고 다음 명령을 실행합니다: Install-Package IronPdf. 그러면 프로젝트에 라이브러리가 추가되고 해당 기능이 활성화됩니다.

IronPDF의 기능에 대해 자세히 알아보려면 어디에서 확인할 수 있나요?

IronPDF의 기능에 대해 자세히 알아보려면 웹사이트의 IronPDF 기능 개요 페이지를 방문하여 자세한 정보와 추가 튜토리얼을 확인하세요.

IronPDF는 .NET 10과 호환되며, .NET 10에서 사용할 때 특별히 고려해야 할 사항이 있나요?

예, IronPDF는 .NET 10과 완벽하게 호환됩니다. 해결 방법 없이 바로 .NET 10을 지원합니다. .NET 10을 사용하면 성능 향상, 비동기/대기 지원, 최신 API 및 크로스 플랫폼 기능을 활용할 수 있습니다. 텍스트를 PDF로 변환하려면 최신 IronPDF NuGet 패키지를 참조하고 평소와 같이 .NET 10 프로젝트에서 ChromePdfRenderer를 사용하세요.

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

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

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