Generating PDF File Using C#

PDF stands for Portable document format. PDFs comprise several things: fonts, graphics, text formatting, images, and OCR text recognition software. To generate a PDF from scratch, we must know how all these components work together and how they interact on the page.

Here, In this article we are going to see how to generate PDFs using C#. We will be cover the following contents in this tutorial. We will create a project in a visual studio. After that, we will install the C# PDF creator library for PDF generation. We can install the library through the NuGet website or from the Visual Studio NuGet Package manager. After that, we will see how we can generate PDF using HTML and CSS with customization like footers e.t.c.

How to create PDF File in C#

  1. Creating C# Project in Visual Studio for PDF Generation
  2. Installing PDF creation C# PDF Library using NuGet Package Manager
  3. Writing code to create PDF documents programmatically.
  4. Create a PDF file from HTML code
  5. Create PDF file from Code
  6. Output of the C# PDF creation library

Let's start creating PDF file programmatically:

Creating C# Project

We will use the Visual Studio 2022 version for creating the C# project. The latest version of Visual Studio is recommended. Open Visual Studio 2022. Follow the following steps for creating a C# project:

  • Open Visual Studio 2022 and click on the "Create Project" button.
  • Now select any C# application templates according to our project requirements. We will use the console application template.
  • Give a name to the C# project.
  • Now, We have to select the .NET framework. We will use the .NET 6.0 for this project. We can choose any framework according to our requirements, but the latest version is recommended.

After that, the project will be created. We can use an already existing project. Now it's time to install the IronPDF .net library, which will be helpful for us to create PDF files.

Installing IronPDF Library

IronPDF is a .NET pdf library that helps us to create and edit PDF files programmatically. It supports .NET 6, .Net 5, .Net Core, .Net Standard and .Net Framework. This can be installed in multiple ways. Here we will install IronPDF using the Package manager console. It is a straightforward way of installing IronPDF. Open the Package manager console and write the following command, and hit enter:

install-package ironpdf

It will install the IronPDF library in our project and will be available.

Writing code to create PDF documents programmatically

Now see the below code. The following code demosnstrate that how we can create PDF files progrmmatically. We can copy code and paste it in our project file.

using IronPdf;
var html = @"
            <h1>HI..! Welcome to the PDF Tutorial!</h1>
            <p> This is 1st Page </p>
            <div style = 'page-break-after: always;' ></div>
            <h2> This is 2nd Page after page break!</h2>
            <div style = 'page-break-after: always;' ></div>
            <p> This is 3rd Page</p>
            <div style = 'page-break-after: always;' ></div>
            <link href=""https://fonts.googleapis.com/css?family=Libre%20Barcode%20128""rel = ""stylesheet"" ><p style = ""font-family: 'Libre Barcode 128', serif; font-size:30px;""> Hello Google Fonts</p>";

// Instantiate Renderer
var Renderer = new IronPdf.ChromePdfRenderer();
using var cover = Renderer.RenderHtmlAsPdf("<h1> This is Cover Page</h1>");

/* Main Document */
//As we have a Cover Page, we're going to start the page numbers at 2.
Renderer.RenderingOptions.FirstPageNumber = 2;

Renderer.RenderingOptions.HtmlFooter = new IronPdf.HtmlHeaderFooter()
{

    MaxHeight = 15, //millimeters
    HtmlFragment = "<center><i>{page} of {total-pages}<i></center>",
    DrawDividerLine = true
};

using PdfDocument Pdf = Renderer.RenderHtmlAsPdf(html);

//Merging PDF document with Cover page
using PdfDocument merge = IronPdf.PdfDocument.Merge(cover, Pdf);

//PDF Settings
merge.SecuritySettings.AllowUserCopyPasteContent = false;
merge.SecuritySettings.UserPassword = "sharable";

merge.SaveAs("combined.pdf");

Let's see how the above code works. Let's divide it into parts:

  • Import IronPDF library
  • Create Content for PDF file in HTML string
  • Instantiate Renderer and create Cover page
  • Add footers and page numbers.
  • Create a PDF file using the IronPDF function
  • Merge PDF file and Cover page
  • Security settings of the PDF file
  • Saving the PDF file

At first, the important step is to import the IronPDF library in the code file to access the functions to create PDF. So, in the first line of the code, We import the IronPDF Library. This convert HTML to PDF file. So, We wrote the PDF page content in an HTML string and added page breaks to add multiple pages at once. The following code line helps to do page breaks.

<div style = 'page-break-after: always;' ></div>

It also supports CSS, so that we can add styling like customize fonts and font colors in the PDF file. Even we can embedd images and barcodes. We add barcode at the last page of the PDF. The following line of code helps to generate Barcode in the PDF file:

<link href=""https://fonts.googleapis.com/css?family=Libre%20Barcode%20128""rel = ""stylesheet"" ><p style = ""font-family: 'Libre Barcode 128', serif; font-size:30px;""> Hello Google Fonts</p>

After that, We instantiate the IronPDF renderer that provides functions to create PDF. We make a cover page and add content to the cover page with an HTML string. After completing the Cover page and assigning it to a variable, We set the starting page of the PDF file to the second by using the FirstPagNumber property.

We add footers in the PDF file, and in footers, We put the total pages and current page number. We use the HtmlFooter property for creating footers and HTML fragments for footer content. After that, We use the RenderHtmlAsPdf function to generate PDF file from an HTML string. After making the PDF file, We merge it with the cover page by using the Merge function, and in parameters, We provide the cover page and pdf document variables name.

Let's come to the second last part. Here We set the security settings for my sample pdf file, which is being created. IronPDF allows setting the User password for opening the PDF file, disabling editing PDF contents, and disabling copying the PDF content.

//PDF Settings
merge.SecuritySettings.AllowUserCopyPasteContent = false;
merge.SecuritySettings.UserPassword = "sharable";

It is a massive benefit if we want to create a classified PDF document. At last, We save the file pdf format by using the SaveAs function, and in the parameter, We provide the file name with the file path.

We can also modify the settings of an already existing pdf document, or we can add multiple things to a new pdf document. It will take just a few lines to do all stuff. It supports converting an HTML file to a PDF file very quickly. We can create a windows form app with a text box and a button to convert text written in the text box to a PDF file.

Output

Let's see the output generated by the above code. When we try to open the generated PDF file, we will get the prompt to enter the password because we've set the password for opening it.

After entering the password, We will first notice the cover page.

And after scrolling, We will be able to see the following pages. We can also notice the footer at the bottom of the page. It shows the current page number and total pages. Total pages include the cover page count too.

On the last page, we will see the barcode we created.

Summary

In this article, We learn how we can generate PDF files using C# at runtime and modify PDF files very easily. We use the IronPDF library, which supports .NET 6, .Net 5, .Net Core, .Net Standard and .Net Framework and it provides good resulting pdf files with just a few lines of code.


Similar Articles