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 own 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:

  • IronPDF

  • 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

The IronPDF is a C# PDF library that provides a set of classes that can be used to create PDF files programmatically. These classes are located in the IronPDF.core 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:

  • Reading and writing of encrypted, compressed, and uncompressed files.
  • Creating new PDF files from scratch or by parsing existing document streams.
  • Applying custom transformations to pages in a document stream before being written to disk as a new file.
  • Encrypting and decrypting PDFs.
  • Merging existing PDF files.
  • Creating and editing PDF forms.
  • Extracting text from a page or document and many other unique features.

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

Steps To Create PDF Files Programmatically:

Firstly, we need to create a new Visual Studio project. I 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 the Visual Studio 2019 version (the latest version is recommended) and C# programming language to build our project. You should have basic knowledge of HTML and C# Language. It is also recommended that you familiarize yourself with Visual Studio.

We will 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 2019.
  • 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. The latest and most stable version of the .net framework is 5.0.

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 Package Solution. This will open the NuGet Package Manager Solution explorer.

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

Method 2: NuGet Package Manager Console

We can use the NuGet Package Manager Console to install our library with ease. It does not require any administrative privilege to install. You will use a NuGet command to install the IronPDF library in your project.

Install-Package IronPDF

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 from this link.

  • 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.

For a more detailed installation guide, visit this link.

Step 3: Add the IronPDF Namespace

Now add the IronPDF namespace to your program. You have to add a given line of code on top of the code.

using IronPDF

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, as provided by 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 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.

string htmlString = "<h1> Generated PDF File!</h1> <p> This file is generated by IronPDF library from HTML String!</p> <p>It is great Library to manipulate PDF Files.</p>";
var Renderer = new ChromePdfRenderer();
Renderer.RenderHtmlAsPdf(htmlString).SaveAs("PDF from HTML String.pdf");
string htmlString = "<h1> Generated PDF File!</h1> <p> This file is generated by IronPDF library from HTML String!</p> <p>It is great Library to manipulate PDF Files.</p>";
var Renderer = new ChromePdfRenderer();
Renderer.RenderHtmlAsPdf(htmlString).SaveAs("PDF from HTML String.pdf");
Dim htmlString As String = "<h1> Generated PDF File!</h1> <p> This file is generated by IronPDF library from HTML String!</p> <p>It is great Library to manipulate PDF Files.</p>"
Dim Renderer = New ChromePdfRenderer()
Renderer.RenderHtmlAsPdf(htmlString).SaveAs("PDF from HTML String.pdf")
VB   C#

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. We use the SaveAs function to save the output PDF file. You can see the output PDF file below.

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:

var Renderer = new ChromePdfRenderer();
var PDF = Renderer.RenderHTMLFileAsPdf("IronFile.html").SaveAs("IronPDF file.pdf");
var Renderer = new ChromePdfRenderer();
var PDF = Renderer.RenderHTMLFileAsPdf("IronFile.html").SaveAs("IronPDF file.pdf");
Dim Renderer = New ChromePdfRenderer()
Dim PDF = Renderer.RenderHTMLFileAsPdf("IronFile.html").SaveAs("IronPDF file.pdf")
VB   C#

We use the RenderHTMLFileAsPdf function to create PDFs from HTML files. This function is the most important function used in the given code sample. 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 save in the bin folder when you run this code. The SaveAs function will help you to 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:

var Renderer = new ChromePdfRenderer();
var PDF = Renderer.RenderUrlAsPdf("https://ironpdf.com/blog/using-ironpdf/csharp-generate-pdf-tutorial/").SaveAs("IronPDF Generate PDF.pdf");
var Renderer = new ChromePdfRenderer();
var PDF = Renderer.RenderUrlAsPdf("https://ironpdf.com/blog/using-ironpdf/csharp-generate-pdf-tutorial/").SaveAs("IronPDF Generate PDF.pdf");
Dim Renderer = New ChromePdfRenderer()
Dim PDF = Renderer.RenderUrlAsPdf("https://ironpdf.com/blog/using-ironpdf/csharp-generate-pdf-tutorial/").SaveAs("IronPDF Generate PDF.pdf")
VB   C#

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:

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 look at 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 of the DLL file according to your choice. You can also use the NuGet Package Manager Console to install it.

3. Now, open any apex 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.

4. Open the Default.aspx.cs file. Add the IronPDF namespace to the file, which is the most important line.

using IronPDF;

5. Write the following line of code in the Page_Load function to create a PDF document of the page.

AspxToPdf.RenderThisPageAsPdf(AspxToPdf.FileBehavior.InBrowser);

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 in our system by adding the following line of code in the Page_Load function:

AspxToPdf.RenderThisPageAsPdf(IronPdf.AspxToPdf.FileBehavior.Attachment);

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 link.

Output:

4.4. Create PDFs Programmatically with Formatting

When creating PDFs, most problems are encountered during the formatting of PDF documents. It isn't easy to format PDF 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 footer 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:

ChromePdfRenderer Renderer = new IronPdf.ChromePdfRenderer();

            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 Setting
            Renderer.RenderingOptions.MarginTop = 40;  
            Renderer.RenderingOptions.MarginLeft = 20;  
            Renderer.RenderingOptions.MarginRight = 20;  
            Renderer.RenderingOptions.MarginBottom = 40;  

            Renderer.RenderingOptions.FirstPageNumber = 1; 

            //Header Setting
            Renderer.RenderingOptions.TextHeader.DrawDividerLine = true;
            Renderer.RenderingOptions.TextHeader.CenterText = "Header!";
            Renderer.RenderingOptions.TextHeader.FontFamily = "Helvetica,Arial";
            Renderer.RenderingOptions.TextHeader.FontSize = 30;

            //Footer Setting
            Renderer.RenderingOptions.TextFooter.DrawDividerLine = true;
            Renderer.RenderingOptions.TextFooter.FontFamily = "Arial";
            Renderer.RenderingOptions.TextFooter.FontSize = 10;
            Renderer.RenderingOptions.TextFooter.LeftText = "{date} {time}";
            Renderer.RenderingOptions.TextFooter.RightText = "{page} of {total-pages}"; 

            string htmlStr = "<h1>PDF Formatting!</h1><h3>Functions and properties for formatting </h3> <p>IronPDF the best ever library for PDF operations and formatting. </p>";
            Renderer.RenderHtmlAsPdf(htmlStr).SaveAs("PDF-Formatted.pdf");
ChromePdfRenderer Renderer = new IronPdf.ChromePdfRenderer();

            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 Setting
            Renderer.RenderingOptions.MarginTop = 40;  
            Renderer.RenderingOptions.MarginLeft = 20;  
            Renderer.RenderingOptions.MarginRight = 20;  
            Renderer.RenderingOptions.MarginBottom = 40;  

            Renderer.RenderingOptions.FirstPageNumber = 1; 

            //Header Setting
            Renderer.RenderingOptions.TextHeader.DrawDividerLine = true;
            Renderer.RenderingOptions.TextHeader.CenterText = "Header!";
            Renderer.RenderingOptions.TextHeader.FontFamily = "Helvetica,Arial";
            Renderer.RenderingOptions.TextHeader.FontSize = 30;

            //Footer Setting
            Renderer.RenderingOptions.TextFooter.DrawDividerLine = true;
            Renderer.RenderingOptions.TextFooter.FontFamily = "Arial";
            Renderer.RenderingOptions.TextFooter.FontSize = 10;
            Renderer.RenderingOptions.TextFooter.LeftText = "{date} {time}";
            Renderer.RenderingOptions.TextFooter.RightText = "{page} of {total-pages}"; 

            string htmlStr = "<h1>PDF Formatting!</h1><h3>Functions and properties for formatting </h3> <p>IronPDF the best ever library for PDF operations and formatting. </p>";
            Renderer.RenderHtmlAsPdf(htmlStr).SaveAs("PDF-Formatted.pdf");
Dim Renderer As ChromePdfRenderer = New IronPdf.ChromePdfRenderer()

			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 Setting
			Renderer.RenderingOptions.MarginTop = 40
			Renderer.RenderingOptions.MarginLeft = 20
			Renderer.RenderingOptions.MarginRight = 20
			Renderer.RenderingOptions.MarginBottom = 40

			Renderer.RenderingOptions.FirstPageNumber = 1

			'Header Setting
			Renderer.RenderingOptions.TextHeader.DrawDividerLine = True
			Renderer.RenderingOptions.TextHeader.CenterText = "Header!"
			Renderer.RenderingOptions.TextHeader.FontFamily = "Helvetica,Arial"
			Renderer.RenderingOptions.TextHeader.FontSize = 30

			'Footer Setting
			Renderer.RenderingOptions.TextFooter.DrawDividerLine = True
			Renderer.RenderingOptions.TextFooter.FontFamily = "Arial"
			Renderer.RenderingOptions.TextFooter.FontSize = 10
			Renderer.RenderingOptions.TextFooter.LeftText = "{date} {time}"
			Renderer.RenderingOptions.TextFooter.RightText = "{page} of {total-pages}"

			Dim htmlStr As String = "<h1>PDF Formatting!</h1><h3>Functions and properties for formatting </h3> <p>IronPDF the best ever library for PDF operations and formatting. </p>"
			Renderer.RenderHtmlAsPdf(htmlStr).SaveAs("PDF-Formatted.pdf")
VB   C#

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 of the PDF file. It can be designated as landscape or portrait.
  • Renderer.RenderingOptions.Title

    • We can use this line to set the title of the PDF file.

For the last lines, we use the RenderHtmlAsPdf function to create a PDF of HTML String, but we can use an HTML file to 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:

Summary:

This tutorial shows how we can create PDF programmatically using the IronPDF C# library. We have seen how to create PDF files from HTML String, HTML file, URL, and ASP.NET web forms. The manipulation and formatting of PDF files becomes 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 30-day trial key 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. More information about licensing can be found at this link.

You can download the software product from this link.