USING IRONPDF

C# Create PDF File Programmatically

For developers, there are many scenarios where the need arises to create PDF files programmatically. You may need to generate PDF reports and other PDF files programmatically in your software. It would be long, expensive, and inefficient to write your code and functions from scratch. This is where IronPDF comes in. Although creating PDF files programmatically in .NET can be frustrating, thankfully, there is now a solution that makes it so much more manageable.

Topics Covered In Tutorial

We will cover the following topics in this tutorial:

Steps to create PDF files programmatically

  • Step 1: Create a C# Project
  • Step 2: Install the IronPdf Library
    • Method 1: NuGet Package Manager
    • Method 2: NuGet Package Manager Console
    • Method 3: Using DLL file
  • Step 3: Add the IronPdf Namespace
  • Step 4: Create a PDF document programmatically
    • 4.1: Create a PDF document programmatically using HTML String
    • 4.2: Create a PDF document programmatically using HTML files
    • 4.3: Create a PDF document programmatically using URL
    • 4.4: Create a PDF document programmatically with formatting
  • Summary

IronPDF

IronPDF is a C# PDF library for .NET developers that provides a set of classes used to create PDF files programmatically. These classes are located in the IronPdf assembly and are designed to be easy to use with any .NET language, including C#, VB.NET, F#, etc. The library offers many functions for creating PDF documents, manipulating existing PDFs, and reading PDFs.

The current version of the IronPDF library supports the following features:

Let's start with how we can use the IronPDF library to create PDFs programmatically in C#.

Steps to Create PDF Files Programmatically

This article will use the Console Application template for this demonstration. You can use any, according to your requirements and choice. You may also use your existing project in which you wish to add a PDF file-generating tool.

Step 1: Create a C# Project

This tutorial will use Visual Studio and the C# programming language to build our project. You should have basic knowledge of HTML and the C# language. It is also recommended that you familiarize yourself with Visual Studio.

Let's look at the multiple methods for creating PDF files programmatically using the IronPDF C# library. Let's begin by creating a C# project.

  • Open Visual Studio.
  • Create a new C# Project or open an existing project.
  • Give a name to the project.
  • Select .Net Core >= 3.1 because 3.1 is supported and works on every device. Recommend the latest version of .Net Core.

Let's move now to Step 2.

Step 2: Install the IronPDF Library

Before proceeding further, we should install the IronPdf library in our project. We can do this in various ways.

Method 1: NuGet Package Manager

We can install the IronPdf C# Library from the NuGet Package Manager. Open the NuGet Package Manager by clicking on Tools > NuGet Package Manager > Manage NuGet Packages for Solution. This will open the NuGet Package Manager Solution Explorer.

C# Create PDF File Programmatically, Figure 1: Open NuGet Package Manager Open NuGet Package Manager

Click on "Browse" and write IronPdf in the search bar. The following result will appear. Select IronPdf and click the Install button; the library will begin installing.

C# Create PDF File Programmatically, Figure 2: Search and install IronPdf package Search and install IronPdf package

Method 2: NuGet Package Manager Console

We can use the NuGet Package Manager Console to install our library quickly. It does not require any administrative privileges to install. You can use a NuGet command to install the IronPdf library in your project.

Install-Package IronPdf

C# Create PDF File Programmatically, Figure 3: Install IronPdf package via Commandline Install IronPdf package via Commandline

Method 3: Using a DLL file

The third way to use IronPDF in your project is to add a DLL file from the IronPDF library. You can download the DLL file.

  • Download the DLL zip file. Extract it to a specific folder.
  • Open a project in Visual Studio. In the Solution Explorer, right-click on References and browse for the IronPDF DLL file.

Visit a more detailed installation guide on how to install IronPDF.

Step 3: Add the IronPdf Namespace

Now add the IronPdf namespace to your program. You need to add the given line of code at the top of the code files you wish to use IronPDF in.

using IronPdf;
using IronPdf;
$vbLabelText   $csharpLabel

This will enable you to access the functions of IronPDF. You must add this line of code to every file where you wish to use the IronPDF features.

Step 4: Create PDF Documents Programmatically

We will look at multiple methods to create PDFs using IronPDF. We will see how easy it is to use simple functions to create PDF files. Let's get started with creating PDFs using HTML string.

4.1. Create PDFs Programmatically using HTML String

In the IronPDF library, HTML is used for styling purposes. You must have basic knowledge of the HTML language to generate PDF documents using the IronPDF library.

The IronPDF library makes it very easy to process HTML strings and convert them into PDF format. Let's look at how to do it using code.

using IronPdf;

IronPdf.License.LicenseKey = "YourLicenseKey";

// HTML content to be converted into a PDF
string htmlString = "<h1> Generated PDF File!</h1> <p> This file is generated by IronPDF library from HTML String!</p> <p>It is a great Library to manipulate PDF Files.</p>";

// Create a PDF renderer
var renderer = new ChromePdfRenderer();

// Convert the HTML string to a PDF and save it
renderer.RenderHtmlAsPdf(htmlString).SaveAs("PDF from HTML String.pdf");
using IronPdf;

IronPdf.License.LicenseKey = "YourLicenseKey";

// HTML content to be converted into a PDF
string htmlString = "<h1> Generated PDF File!</h1> <p> This file is generated by IronPDF library from HTML String!</p> <p>It is a great Library to manipulate PDF Files.</p>";

// Create a PDF renderer
var renderer = new ChromePdfRenderer();

// Convert the HTML string to a PDF and save it
renderer.RenderHtmlAsPdf(htmlString).SaveAs("PDF from HTML String.pdf");
$vbLabelText   $csharpLabel

This code will generate a PDF file containing the content stored in the htmlString variable. In this code sample, the RenderHtmlAsPdf function has been used. This function performs the conversion of HTML String to a PDF document.

You must be familiar with HTML tags to generate PDF files using the IronPDF library. The SaveAs function is used to save the output PDF file. You can see the output PDF file below.

Output:

C# Create PDF File Programmatically, Figure 4: PDF file output PDF file output

4.2. Create PDFs Programmatically using HTML Files

The IronPDF library provides a fantastic feature to create a PDF file from an HTML file. IronPDF directly converts everything in an HTML file, including images, CSS, forms, etc. to a PDF document. It does not require any other library or function for further processing. IronPDF directly converts any HTML file to a PDF file.

Let's look at some sample code for creating a PDF file from an HTML file:

using IronPdf;

IronPdf.License.LicenseKey = "YourLicenseKey";

// Create a PDF renderer
var renderer = new ChromePdfRenderer();

// Convert an HTML file to a PDF and save it
var pdf = renderer.RenderHtmlFileAsPdf("IronFile.html").SaveAs("IronPDF file.pdf");
using IronPdf;

IronPdf.License.LicenseKey = "YourLicenseKey";

// Create a PDF renderer
var renderer = new ChromePdfRenderer();

// Convert an HTML file to a PDF and save it
var pdf = renderer.RenderHtmlFileAsPdf("IronFile.html").SaveAs("IronPDF file.pdf");
$vbLabelText   $csharpLabel

We use the RenderHtmlFileAsPdf function to create PDFs from HTML files. You can give the HTML File location in the function parameter or put the HTML file in the bin folder of the source code, so you will only need to put the file name with extension in the RenderHtmlFileAsPdf function's parameter. The output PDF file will be saved in the bin folder when you run this code. The SaveAs function helps save created PDF files.

4.3. Create PDFs Programmatically using URLs

Sometimes we need to create PDF files of a URL programmatically in our program. This can be a very technical task if we code everything from scratch. IronPDF helps us here by providing an excellent function for creating PDFs from URLs. You can use any URL to create a PDF.

Let's examine how to do it:

using IronPdf;

IronPdf.License.LicenseKey = "YourLicenseKey";

// Create a PDF renderer
var renderer = new ChromePdfRenderer();

// Convert a URL to a PDF and save it
var pdf = renderer.RenderUrlAsPdf("https://ironpdf.com/blog/using-ironpdf/csharp-generate-pdf-tutorial/").SaveAs("IronPDF Generate PDF.pdf");
using IronPdf;

IronPdf.License.LicenseKey = "YourLicenseKey";

// Create a PDF renderer
var renderer = new ChromePdfRenderer();

// Convert a URL to a PDF and save it
var pdf = renderer.RenderUrlAsPdf("https://ironpdf.com/blog/using-ironpdf/csharp-generate-pdf-tutorial/").SaveAs("IronPDF Generate PDF.pdf");
$vbLabelText   $csharpLabel

The above code will create a PDF of the given URL parameter to the RenderUrlAsPdf function. This function creates a PDF of the URL. This would otherwise be a very complex task if you attempted to do it from scratch, so IronPDF provides developers with a simple process to convert any URL to a PDF. The SaveAs function is used for saving output files in the bin folder. To set the file format to PDF, you must specify a .pdf extension with a file name parameter in the SaveAs function. You can see the bin folder in your project folder. The output is displayed below.

Output:

C# Create PDF File Programmatically, Figure 5: Create PDF file from URL Create PDF file from URL

4.4. Create PDFs Programmatically using ASP.NET Web Forms

ASP.NET is a server-side programming framework that extends the functionality of HTML and supports web development in a browser. ASP.NET pages are written in HTML, CSS, and JavaScript, and can be coded as ASPX files (.aspx). ASP.NET web forms create user-friendly, functionality-rich websites, online banking, intranets, and accounting systems.

We will use the IronPDF library to convert ASP.NET web forms to PDF. Initially rendered as a web page, we will transform this into a PDF to view and download in a web browser. We will use the AspxToPdf class of IronPDF to complete the conversion.

Let's see how to do it:

  1. Create an ASP.NET web form project in Visual Studio. The latest version of Visual Studio is recommended.
  2. Install the IronPDF library using the NuGet Package Manager or the DLL file according to your choice. You can also use the NuGet Package Manager Console to install it.
  3. Now, open any ASPX web page's code that you want to convert into a PDF file. Here we will create a PDF of the Default.aspx page of the project.

C# Create PDF File Programmatically, Figure 6: Web Form project structure in Visual Studio Web Form project structure in Visual Studio

  1. Open the Default.aspx.cs file. Add the IronPdf namespace to the file, which is the most important line.
using IronPdf;
using IronPdf;
$vbLabelText   $csharpLabel
  1. Write the following line of code in the Page_Load function to create a PDF document of the page.
AspxToPdf.RenderThisPageAsPdf(AspxToPdf.FileBehavior.InBrowser);
AspxToPdf.RenderThisPageAsPdf(AspxToPdf.FileBehavior.InBrowser);
$vbLabelText   $csharpLabel

And that's it! A PDF file of the ASPX webpage has been created. When you run the project, you will see a PDF of the web page in the browser. The result is the same as when you make a PDF by pressing Ctrl+P. Here you didn't need to press Ctrl+P to create a PDF of the ASPX file.

This has been done on the server-side. In this code, we use the AspxToPdf class of IronPDF. The RenderThisPageAsPdf function creates the PDF of the ASPX webpage.

The above code shows the PDF file in the browser. We can download the PDF file directly to our system by adding the following line of code in the Page_Load function:

AspxToPdf.RenderThisPageAsPdf(IronPdf.AspxToPdf.FileBehavior.Attachment);
AspxToPdf.RenderThisPageAsPdf(IronPdf.AspxToPdf.FileBehavior.Attachment);
$vbLabelText   $csharpLabel

This code will download the PDF file of the ASPX web page in the system. We can also set the name of the ASPX PDF file. There are multiple options available for modifications and formatting, such as headers, footers, printing options, quality, etc. For more details, visit this comprehensive ASPX to PDF tutorial.

Output:

C# Create PDF File Programmatically, Figure 7: Output of rendering a PDF file from server-side Output of rendering a PDF file from server-side

Explore the latest Microsoft technology for Blazor application to create PDF files

4.5. Create PDFs Programmatically with Formatting

When creating PDFs, most problems are encountered during the formatting of PDF documents. It isn't easy to format PDFs programmatically. But, we now have a solution in the shape of IronPDF. IronPDF assists with various formatting options to allow us to customize the PDF file we are creating. It provides us with methods to add headers, footers, margins, and many other formatting options.

Using IronPDF enables us to set page orientation, page size, and titles. It also supports the changing of font size, font color, font type, and other font-related operations. You can add footers and headers with a divider line and custom text. Let's look at how to customize PDF files using IronPDF.

  • Create a C# console project. You can create a GUI project, too, depending on your requirements. You can also open existing projects.
  • Install the IronPDF library using NuGet Package Manager or the DLL file.
  • Add the IronPDF namespace on top of the code file.

Our setup of the application is now completed. Next, add the following code to the PDF file:

using IronPdf;

IronPdf.License.LicenseKey = "YourLicenseKey";

// Create a PDF renderer
ChromePdfRenderer renderer = new IronPdf.ChromePdfRenderer();

// Configure rendering options
renderer.RenderingOptions.PaperOrientation = IronPdf.Rendering.PdfPaperOrientation.Portrait;
renderer.RenderingOptions.SetCustomPaperSizeInInches(14, 40);
renderer.RenderingOptions.PrintHtmlBackgrounds = true;
renderer.RenderingOptions.Title = "PDF Generated";
renderer.RenderingOptions.Zoom = 100;

// Margin Settings
renderer.RenderingOptions.MarginTop = 40;  
renderer.RenderingOptions.MarginLeft = 20;  
renderer.RenderingOptions.MarginRight = 20;  
renderer.RenderingOptions.MarginBottom = 40;  

renderer.RenderingOptions.FirstPageNumber = 1; 

// Header Settings
renderer.RenderingOptions.TextHeader.DrawDividerLine = true;
renderer.RenderingOptions.TextHeader.CenterText = "Header!";
renderer.RenderingOptions.TextHeader.Font = IronSoftware.Drawing.FontTypes.Helvetica;

// Footer Settings
renderer.RenderingOptions.TextFooter.DrawDividerLine = true;
renderer.RenderingOptions.TextFooter.Font = IronSoftware.Drawing.FontTypes.Arial;
renderer.RenderingOptions.TextFooter.FontSize = 10;
renderer.RenderingOptions.TextFooter.LeftText = "{date} {time}";
renderer.RenderingOptions.TextFooter.RightText = "{page} of {total-pages}"; 

// HTML content to be converted into a PDF
string htmlStr = "<h1>PDF Formatting!</h1><h3>Functions and properties for formatting </h3> <p>IronPDF is the best ever library for PDF operations and formatting. </p>";

// Convert the HTML string to a PDF and save it
renderer.RenderHtmlAsPdf(htmlStr).SaveAs("PDF-Formatted.pdf");
using IronPdf;

IronPdf.License.LicenseKey = "YourLicenseKey";

// Create a PDF renderer
ChromePdfRenderer renderer = new IronPdf.ChromePdfRenderer();

// Configure rendering options
renderer.RenderingOptions.PaperOrientation = IronPdf.Rendering.PdfPaperOrientation.Portrait;
renderer.RenderingOptions.SetCustomPaperSizeInInches(14, 40);
renderer.RenderingOptions.PrintHtmlBackgrounds = true;
renderer.RenderingOptions.Title = "PDF Generated";
renderer.RenderingOptions.Zoom = 100;

// Margin Settings
renderer.RenderingOptions.MarginTop = 40;  
renderer.RenderingOptions.MarginLeft = 20;  
renderer.RenderingOptions.MarginRight = 20;  
renderer.RenderingOptions.MarginBottom = 40;  

renderer.RenderingOptions.FirstPageNumber = 1; 

// Header Settings
renderer.RenderingOptions.TextHeader.DrawDividerLine = true;
renderer.RenderingOptions.TextHeader.CenterText = "Header!";
renderer.RenderingOptions.TextHeader.Font = IronSoftware.Drawing.FontTypes.Helvetica;

// Footer Settings
renderer.RenderingOptions.TextFooter.DrawDividerLine = true;
renderer.RenderingOptions.TextFooter.Font = IronSoftware.Drawing.FontTypes.Arial;
renderer.RenderingOptions.TextFooter.FontSize = 10;
renderer.RenderingOptions.TextFooter.LeftText = "{date} {time}";
renderer.RenderingOptions.TextFooter.RightText = "{page} of {total-pages}"; 

// HTML content to be converted into a PDF
string htmlStr = "<h1>PDF Formatting!</h1><h3>Functions and properties for formatting </h3> <p>IronPDF is the best ever library for PDF operations and formatting. </p>";

// Convert the HTML string to a PDF and save it
renderer.RenderHtmlAsPdf(htmlStr).SaveAs("PDF-Formatted.pdf");
$vbLabelText   $csharpLabel

This piece of code is formatting the PDF files. RenderingOptions is the primary tool to set different properties while creating PDF documents.

  • renderer.RenderingOptions.TextHeader
    • This line of code is used to set up the PDF file's header. You can access more properties for the header with this line of code.
  • renderer.RenderingOptions.TextFooter
    • This line of code sets up the footer properties such as text, right and left side of the footer, font size, and many others.
  • renderer.RenderingOptions.PaperOrientation
    • This line of code enables the user to set the page orientation (landscape or portrait) of the PDF file.
  • renderer.RenderingOptions.Title
    • We can use this line to set the title of the PDF file.

In the last lines, we use the RenderHtmlAsPdf function to create a PDF of an HTML String, but we can use an HTML file to seamlessly convert it into PDF while preserving the current formatting. This is a very handy feature of IronPDF that gives you complete freedom to customize everything to do with PDF documents.

Output:

C# Create PDF File Programmatically, Figure 8: PDF output with formatting support PDF output with formatting support

Summary

This tutorial shows how we can create PDFs programmatically using the IronPDF C# library. We have seen how to create PDF files from HTML String, HTML files, URLs, and ASP.NET web forms. The manipulation and formatting of PDF files become very easy with the IronPDF library function. All that is required is just a few lines of code to create and format the PDF file programmatically. IronPDF is ideal for developers and companies who need to manipulate PDF files within their software.

You can try the free version to test it out, and there is a free trial key available that doesn't require any credit card payments. Further, the current special offer allows you to get five products by IronPDF for the price of just two.

Frequently Asked Questions

What is IronPDF?

IronPDF is a C# PDF library for .NET developers that provides a set of classes used to create and manipulate PDF files programmatically. It is designed to be easy to use with any .NET language, including C#, VB.NET, and F#.

How can I install the IronPDF library in my C# project?

You can install the IronPDF library using the NuGet Package Manager, the NuGet Package Manager Console, or by adding a DLL file. Each method provides a straightforward way to integrate IronPDF into your project.

What are the steps to create a PDF file programmatically using IronPDF?

The main steps include creating a C# project, installing the IronPDF library, adding the IronPDF namespace, and using IronPDF functions to create and save PDF documents from HTML strings, HTML files, or URLs.

Can IronPDF create PDFs from HTML files?

Yes, IronPDF can convert HTML files directly into PDF documents without requiring additional processing, making it a powerful tool for creating PDFs with complex layouts and styles.

Is it possible to create PDF documents with custom formatting using IronPDF?

Yes, IronPDF provides various formatting options, including setting page orientation, paper size, headers, footers, and more. These options allow for detailed customization of the PDF output.

Can IronPDF handle encrypted PDF files?

Yes, IronPDF supports reading and writing encrypted PDF files, allowing developers to encrypt and decrypt PDF documents as needed.

How do I create a PDF from a URL using IronPDF?

You can use the 'RenderUrlAsPdf' function in IronPDF to convert a web page URL into a PDF document quickly and efficiently.

Does IronPDF support merging existing PDF files?

Yes, IronPDF provides functionality to seamlessly merge existing PDF files, making it easy to combine multiple documents into a single PDF.

What are the prerequisites for using IronPDF in a project?

You should have basic knowledge of the C# programming language and familiarity with Visual Studio. Understanding HTML is beneficial when creating PDFs from HTML content.

Is there a free trial available for IronPDF?

Yes, IronPDF offers a free trial that allows developers to test its features without requiring any credit card payments.

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.
< PREVIOUS
Comprehensive Guide to C# PDF Generator: Using IronPDF for Effortless PDF Creation & Manipulation
NEXT >
How to Open a PDF File in C#