Skip to footer content
USING IRONPDF

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;
Imports 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");
' Create an instance of ChromePdfRenderer, which is responsible for rendering HTML into PDF
Dim renderer As New ChromePdfRenderer()

' Render a simple HTML string as a PDF document
Dim pdf As PdfDocument = 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;
Imports 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");
' Read all text from a TXT file into a string
Dim text As String = File.ReadAllText("D:\Iron Software\textToPDF\myTxtFile.txt")

' Use the ChromePdfRenderer to render the text as a PDF document
Dim renderer As New ChromePdfRenderer()
Dim pdf As PdfDocument = 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");
' 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();
' 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");
    }
}
Imports IronOcr

Friend Class Program
	Shared Sub Main(ByVal args() As String)

		' Create an instance of the OCR Tesseract
		Dim ocr = New IronTesseract()

		' Enable searchable PDF output
		ocr.Configuration.RenderSearchablePdf = True

		' Load a scanned document image
		Dim input = New OcrInput()
		input.LoadImage("sample-page.png")

		' Perform OCR on the scanned document
		Dim result As OcrResult = ocr.Read(input)

		' Output the recognized text
		Console.WriteLine(result.Text)

		' Save the recognized text to a file
		result.SaveAsSearchablePdf("output.pdf")
	End Sub
End Class
$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. IronSoftware 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.

Frequently Asked Questions

What is this library and how does it relate to .NET technology?

IronPDF is a .NET library designed for generating, reading, editing, and saving PDF files in .NET projects. It supports various .NET frameworks and provides features such as converting text to PDF, adding watermarks, and printing PDFs.

How can I convert text to PDF using C#?

To convert text to PDF using C#, you need to install IronPDF, reference it in your project, and use the ChromePdfRenderer class to render HTML or text as a PDF. You can then save the PDF using the SaveAs method.

What are the use cases for converting text to PDF?

Converting text to PDF can be useful for making reports, converting invoices, creating text editors and fillable PDF forms, and transforming text files into PDF files.

How do I install this library in a Visual Studio project?

To install IronPDF in Visual Studio, open the Package Manager Console and run the command: Install-Package IronPdf. This will add IronPDF to your project, enabling its functionalities.

Can I add a watermark to a PDF using this library?

Yes, you can add a watermark to a PDF using IronPDF by using the ApplyWatermark method on the PdfDocument object. You can specify the text, rotation, and alignment properties of the watermark.

Is it possible to print PDFs using this library?

Yes, you can print PDFs using IronPDF by calling the Print method on a PdfDocument object. This sends the PDF to the default printer.

What are the benefits of using this library for text to PDF conversion?

IronPDF offers a developer-friendly approach with high performance and ease of use. It supports multiple .NET frameworks and provides a wide range of features in a single library, requiring minimal code to perform complex tasks.

How do I convert a TXT file to a PDF using this library?

To convert a TXT file to a PDF, read the text from the file using File.ReadAllText, then use the ChromePdfRenderer to render it as a PDF. Save the resulting PDF using the SaveAs method.

What other features does this library provide?

Besides converting text to PDFs, IronPDF can render charts, add barcodes, enhance security with passwords, and handle PDF forms, among other features.

Where can I find more information about this library's features?

For more information about IronPDF's features, you can visit the IronPDF Feature Overview page on their website.

Chipego
Software Engineer
Chipego has a natural skill for listening that helps him to comprehend customer issues, and offer intelligent solutions. He joined the Iron Software team in 2023, after studying a Bachelor of Science in Information Technology. IronPDF and IronOCR are the two products Chipego has been focusing on, but his knowledge of all products is growing daily, as he finds new ways to support customers. He enjoys how collaborative life is at Iron Software, with team members from across the company bringing their varied experience to contribute to effective, innovative solutions. When Chipego is away from his desk, he can often be found enjoying a good book or playing football.