Generating PDFs in C#

.NET Core PDF Generator

Creating .NET Core PDF files is a cumbersome task. Working with PDFs in ASP.NET MVC projects, as well as converting MVC views, HTML files, and online web pages to PDF can be challenging. This tutorial works with the IronPDF tool to tackle these problems, providing instructional guidelines for many of your PDF .NET needs.

IronPDF also supports debugging of your HTML with Chrome for Pixel Perfect PDFs. A tutorial for setting this up can be found here.


Overview

After this tutorial, you'll be able to:

  • Convert to PDF from different sources like URL, HTML, MVC views
  • Engage with advanced options used for different output PDF settings
  • Deploy your project to Linux and Windows
  • Work with PDF document manipulation capabilities
  • Add headers and footers, merge files, add stamps
  • Work with Dockers

This wide range of .NET Core HTML to PDF capabilities will help with a whole range of project needs.


Step 1

1. Install the IronPDF Library Free

C# NuGet Library for PDF

Install with NuGet

Install-Package IronPdf
or
C# PDF DLL

Download DLL

Download DLL

Manually install into your project

IronPDF can be installed and used on all of the .NET project types like Windows applications, ASP.NET MVC, and .NET Core applications.

To add the IronPDF library to our project we have two ways, either from the Visual Studio editor install using NuGet, or with a command line using package console manager.

Install using NuGet

To add the IronPDF library to our project using NuGet, we can use the visualized interface (NuGet Package Manager) or by command using Package Manager Console:

1.1.1 Using NuGet Package Manager

1- Right click on project name -> Select Manage NuGet Package 2- From browser tab -> search for IronPdf -> Install 3- Click Ok 4- Done!

1.1.2 Using NuGet Package Console manager

1- From Tools -> NuGet Package Manager -> Package Manager Console 2- Run command -> Install-Package IronPdf


How To Tutorials

2. Convert Website to PDF

Sample: ConvertUrlToPdf console application

Follow these steps to create a new Asp.NET MVC Project


1- Open Visual Studio 2- Choose Create new project 3- Choose Console App (.NET Core) 4- Give our sample name “ConvertUrlToPdf” and click create 5- Now we have a console application created 6- Add IronPdf => click install

7- Add our first few lines that render a Wikipedia website main page to PDF

:path=/static-assets/pdf/content-code-examples/tutorials/dotnet-core-pdf-generating-1.cs
Console.WriteLine("Hello World!");
ChromePdfRenderer renderer = new ChromePdfRenderer();
PdfDocument pdf = renderer.RenderUrlAsPdf("https://www.wikipedia.org/");
pdf.SaveAs("wiki.pdf");
Console.WriteLine("Hello World!")
Dim renderer As New ChromePdfRenderer()
Dim pdf As PdfDocument = renderer.RenderUrlAsPdf("https://www.wikipedia.org/")
pdf.SaveAs("wiki.pdf")
VB   C#

8- Run and check created file wiki.pdf


3. Convert .NET Core HTML to PDF

Sample: ConvertHTMLToPdf Console application

To render HTML to PDF we have two ways:
1- Write HTML into string then render it
2- Write HTML into file and pass it path to IronPDF to render it

Rendering the HTML string sample code will look like this.

:path=/static-assets/pdf/content-code-examples/tutorials/dotnet-core-pdf-generating-2.cs
ChromePdfRenderer renderer = new ChromePdfRenderer();
PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>Hello IronPdf</h1>");
pdf.SaveAs("HtmlString.pdf");
Dim renderer As New ChromePdfRenderer()
Dim pdf As PdfDocument = renderer.RenderHtmlAsPdf("<h1>Hello IronPdf</h1>")
pdf.SaveAs("HtmlString.pdf")
VB   C#

And the Resulting PDF will look like this.


4. Convert MVC View to PDF

Sample: TicketsApps .NET Core MVC Application

Let’s implement this real life example. I chose an online ticketing site. You open the site, and navigate to book ticket, then fill in the required information, and then you get your copy as a downloadable PDF file.

We will go through these steps: -
1- Create client object model
2- Create client services (add, view)
3- Add pages (register, view)
4- Download PDF ticket

So now, I will start by creating the client object model.

1- Choose ASP.NET core web applications 2- Name the project “TicketsApps” 3- Choose “.NET Core”, “ASP.NET core 3.1” , “Web Application (Model-View-Controller)”, check enable Docker, and choose Linux Image 4- Now it’s ready, 5- Right click on models’ folders, choose to add class 6- Name the model “ClientModel” then click add

7- Add to ClientModel the attributes name, phone, and email, and make them all required by adding required an attribute over them as follows

:path=/static-assets/pdf/content-code-examples/tutorials/dotnet-core-pdf-generating-3.cs
public class ClientModel
{
    [Required]
    public string Name { get; set; }
    [Required]
    public string Phone { get; set; }
    [Required]
    public string Email { get; set; }
}
Public Class ClientModel
	<Required>
	Public Property Name() As String
	<Required>
	Public Property Phone() As String
	<Required>
	Public Property Email() As String
End Class
VB   C#

8- Step 2, add services a. Create folder and with the name “services”
b. Then add class with the name “ClientServices”
c. Add static object of type “ClientModel” to use it as a repository
d. Add two functions, one for saving client to repository, and the second to get saved clients

:path=/static-assets/pdf/content-code-examples/tutorials/dotnet-core-pdf-generating-4.cs
public class ClientServices
{
    private static ClientModel _clientModel;
    public static void AddClient(ClientModel clientModel)
    {
        _clientModel = clientModel;
    }
    public static ClientModel GetClient()
    {
        return _clientModel;
    }
}
Public Class ClientServices
	Private Shared _clientModel As ClientModel
	Public Shared Sub AddClient(ByVal clientModel As ClientModel)
		_clientModel = clientModel
	End Sub
	Public Shared Function GetClient() As ClientModel
		Return _clientModel
	End Function
End Class
VB   C#

9- Step three, the book your ticket page

10- From solution explorer, right click over controller folder, choose add, then choose controller 11- Name it BookTicketController 12- Right click on index function (or as we called it action) and choose add view to add html 13- Set view name “index,” then click add 14- Using the mouse right click over folder views -> Home, and select home 15- Add index view

16- Update the HTML as follows

:path=/static-assets/pdf/content-code-examples/tutorials/dotnet-core-pdf-generating-5.cs
@model IronPdfMVCHelloWorld.Models.ClientModel
@{
  ViewBag.Title = "Book Ticket";
}
<h2>Index</h2>
@using (Html.BeginForm())
{
  <div class="form-horizontal">
    @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    <div class="form-group">
      @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
      <div class="col-md-10">
        @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
        @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
      </div>
    </div>
    <div class="form-group">
      @Html.LabelFor(model => model.Phone, htmlAttributes: new { @class = "control-label col-md-2" })
      <div class="col-md-10">
        @Html.EditorFor(model => model.Phone, new { htmlAttributes = new { @class = "form-control" } })
        @Html.ValidationMessageFor(model => model.Phone, "", new { @class = "text-danger" })
      </div>
    </div>
    <div class="form-group">
      @Html.LabelFor(model => model.Email, htmlAttributes: new { @class = "control-label col-md-2" })
      <div class="col-md-10">
        @Html.EditorFor(model => model.Email, new { htmlAttributes = new { @class = "form-control" } })
        @Html.ValidationMessageFor(model => model.Email, "", new { @class = "text-danger" })
      </div>
    </div>
    <div class="form-group">
      <div class="col-md-10 pull-right">
        <button type="submit" value="Save" class="btn btn-sm">
          <i class="fa fa-plus"></i>
          <span>
            Save
          </span>
        </button>
      </div>
    </div>
  </div>
}
model ReadOnly Property () As IronPdfMVCHelloWorld.Models.ClientModel
  ViewBag.Title = "Book Ticket"
End Property
'INSTANT VB TODO TASK: The following line could not be converted:
(Of h2) Index</h2> [using](Html.BeginForm())
If True Then
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'  <div class="form-horizontal"> @Html.ValidationSummary(True, "", New { @class = "text-danger" }) <div class="form-group"> @Html.LabelFor(model => model.Name, htmlAttributes: New { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.EditorFor(model => model.Name, New { htmlAttributes = New { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.Name, "", New { @class = "text-danger" }) </div> </div> <div class="form-group"> @Html.LabelFor(model => model.Phone, htmlAttributes: New { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.EditorFor(model => model.Phone, New { htmlAttributes = New { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.Phone, "", New { @class = "text-danger" }) </div> </div> <div class="form-group"> @Html.LabelFor(model => model.Email, htmlAttributes: New { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.EditorFor(model => model.Email, New { htmlAttributes = New { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.Email, "", New { @class = "text-danger" }) </div> </div> <div class="form-group"> <div class="col-md-10 pull-right"> <button type="submit" value="Save" class="btn btn-sm"> <i class="fa fa-plus"></i> <span> Save </span> </button> </div> </div> </div> }
VB   C#

17- Add a link to BookTicket Page to enable our website visitors to navigate to our new booking page by updating layout in existing path (view-> shared-> layout.chtml)

<li><a class="nav-link text-dark" asp-area="" asp-controller="BookTicket" aspaction="Index">Book Ticket</a></li>
<li><a class="nav-link text-dark" asp-area="" asp-controller="BookTicket" aspaction="Index">Book Ticket</a></li>
HTML

18- The result should look like this. 19- Navigate to the book ticket page by clicking on its link. You should find that it looks like this

20- Now let’s add the action that will validate and save the booking information

21- Add another index action with the attribute [HttpPost] to inform the MVC engine that this action is for submitting data. I validate the sent model, and if it's valid the code will redirect the visitor to TicketView Page. If it's not valid, the visitor will receive error validation messages on screen.

:path=/static-assets/pdf/content-code-examples/tutorials/dotnet-core-pdf-generating-7.cs
[HttpPost]
public ActionResult Index(ClientModel model)
{
    if (ModelState.IsValid)
    {
        ClientServices.AddClient(model);
        Return RedirectToAction("TicketView");
    }
  return View(model);
}
<HttpPost>
Public Function Index(ByVal model As ClientModel) As ActionResult
	If ModelState.IsValid Then
		ClientServices.AddClient(model)
		[Return] RedirectToAction("TicketView")
	End If
  Return View(model)
End Function
VB   C#

Sample of error messages

22- Add TicketView to display our ticket

:path=/static-assets/pdf/content-code-examples/tutorials/dotnet-core-pdf-generating-8.cs
public ActionResult TicketView()
{
    var ticket = ClientServices.GetClient();
    return View(ticket);
}
Public Function TicketView() As ActionResult
	Dim ticket = ClientServices.GetClient()
	Return View(ticket)
End Function
VB   C#

23- Add its view

24- This view will host a Ticket partial view that is responsible to display the ticket and will be used later to print Ticket

25- Add ticket model

26- Use the Ticket model code as follows

:path=/static-assets/pdf/content-code-examples/tutorials/dotnet-core-pdf-generating-9.cs
public class TicketModel : ClientModel
{
    public int TicketNumber { get; set; }
    public DateTime TicketDate { get; set; }
}
Public Class TicketModel
	Inherits ClientModel

	Public Property TicketNumber() As Integer
	Public Property TicketDate() As DateTime
End Class
VB   C#

27- Add IronPDF to project 28- Click OK

29- Add the TicketView post method that will handle the download button

:path=/static-assets/pdf/content-code-examples/tutorials/dotnet-core-pdf-generating-10.cs
[HttpPost]
public ActionResult TicketView(TicketModel model)
{
    IronPdf.Installation.TempFolderPath = $@"{_host.ContentRootPath}/irontemp/";
    IronPdf.Installation.LinuxAndDockerDependenciesAutoConfig = true;
    var html = this.RenderViewAsync("_TicketPdf", model);
    var ironPdfRender = new IronPdf.ChromePdfRenderer();
    using var pdfDoc = ironPdfRender.RenderHtmlAsPdf(html.Result);
    return File(pdfDoc.Stream.ToArray(), "application/pdf");
}
<HttpPost>
Public Function TicketView(ByVal model As TicketModel) As ActionResult
	IronPdf.Installation.TempFolderPath = $"{_host.ContentRootPath}/irontemp/"
	IronPdf.Installation.LinuxAndDockerDependenciesAutoConfig = True
	Dim html = Me.RenderViewAsync("_TicketPdf", model)
	Dim ironPdfRender = New IronPdf.ChromePdfRenderer()
	Dim pdfDoc = ironPdfRender.RenderHtmlAsPdf(html.Result)
	Return File(pdfDoc.Stream.ToArray(), "application/pdf")
End Function
VB   C#

30- Add the controller extension that will render partial view to string

31- Use the Extension code as follows

:path=/static-assets/pdf/content-code-examples/tutorials/dotnet-core-pdf-generating-11.cs
using System.IO;
using System.Threading.Tasks;

public static class ControllerExtensions
{
    public static async Task<string> RenderViewAsync<TModel>(this Controller controller, string viewName, TModel model, bool partial = false)
    {
        if (string.IsNullOrEmpty(viewName))
        {
            viewName = controller.ControllerContext.ActionDescriptor.ActionName;
        }
        controller.ViewData.Model = model;
        using (var writer = new StringWriter())
        {
            IViewEngine viewEngine = controller.HttpContext.RequestServices.GetService(typeof(ICompositeViewEngine)) as ICompositeViewEngine;
            ViewEngineResult viewResult = viewEngine.FindView(controller.ControllerContext, viewName, !partial);
            if (viewResult.Success == false)
            {
                return $"A view with the name {viewName} could not be found";
            }
            ViewContext viewContext = new ViewContext(controller.ControllerContext, viewResult.View, controller.ViewData, controller.TempData, writer, new HtmlHelperOptions());
            await viewResult.View.RenderAsync(viewContext);
            return writer.GetStringBuilder().ToString();
        }
    }
}
Imports System.IO
Imports System.Threading.Tasks

Public Module ControllerExtensions
	<System.Runtime.CompilerServices.Extension> _
	Public Async Function RenderViewAsync(Of TModel)(ByVal controller As Controller, ByVal viewName As String, ByVal model As TModel, Optional ByVal As Boolean = False) As Task(Of String)
		If String.IsNullOrEmpty(viewName) Then
			viewName = controller.ControllerContext.ActionDescriptor.ActionName
		End If
		controller.ViewData.Model = model
		Using writer = New StringWriter()
			Dim viewEngine As IViewEngine = TryCast(controller.HttpContext.RequestServices.GetService(GetType(ICompositeViewEngine)), ICompositeViewEngine)
			Dim viewResult As ViewEngineResult = viewEngine.FindView(controller.ControllerContext, viewName, Not partial)
			If viewResult.Success = False Then
				Return $"A view with the name {viewName} could not be found"
			End If
			Dim viewContext As New ViewContext(controller.ControllerContext, viewResult.View, controller.ViewData, controller.TempData, writer, New HtmlHelperOptions())
			Await viewResult.View.RenderAsync(viewContext)
			Return writer.GetStringBuilder().ToString()
		End Using
	End Function
End Module
VB   C#

32- Run and file ticket information, then click save 33- View ticket

34- To download the ticket as PDF, click download. You will get a PDF containing the ticket.


5. .NET PDF Render Options Chart

We have some advanced options that define PDF-rendering options like adjusting margins, paper orientation, paper size, and more.

Below is a table to illustrate the many different options.

ClassChromePdfRenderer
DescriptionUsed to define PDF print out options, like paper size, DPI, headers and footers
Properties / functionsTypeDescription
CreatePdfFormsFromHtmlBooleanTurns all HTML form elements into editable PDF form
CssMediaTypeEnum
PdfCssMediaType
{
Print=0,
Screen=1
}
Enable media=”Screen”,Css Styles and stylsheets.
Note: By setting Allow
ScreenCss=false; IronPDF prints using CSS for media=”print” only.
CustomCssUrlUriAllow Custom CSS Style sheets to be applied on HTML before rendering. You may set it to remote URL or local file path.
DPIintDefine the number of print out DPI (Dot Per Inch). The standard value is 300 DPI. Increasing DPI value make images and text output more clear but increases PDF file size.
EnableJavaScriptBooleanBy default its value = false. It enables\disables JavaScript and JSON execution for 100ms before page is rendered. Great option for printing from client scripting frameworks that use JavaScript for its operations, like Ajax or angular or equivalent frameworks.
FirstPageNumberintUsed with page header or footer to set the first page start number.
FitToPaperWidthBooleanSetToPaperWidth=true will force IronPDF to fit rendered content into one page, only if it's possible
TextFooterTextHeaderFooterSet the footer content see Header PdfHeaderFooter Class
TextHeader
HtmlFooterHtmlHeaderFooterSet the footer content see HtmlHeaderFooter Class
HtmHeader
LicenseKeyStringSet license key and remove watermark
MarginBottomintBottom paper margin in millimeter, set to zero for borderless
MarginLeftintLeft paper margin in millimeter , set to zero for borderless
MarginRightintRight paper margin in millimeter , set to zero for borderless
MarginTopintTop paper margin in millimeter , set to zero for borderless
PaperOrientationEnum
PdfPaperOrientation
{
Portrait, Landscape
}
Set output PDF orientation
PaperSizeEnum PdfPaperSizeSet output PDF page size (A4, A3, etc.)
PrintHtmlBackgroundsBooleanPrint background color and images from HTML
RenderDelayintSet waiting milliseconds before rendering html, this option useful when used to render pages contain animation or Ajax.
TitlestringCan set PDF title and metadata title
ZoomstringSet enlarge zoom level (%) for rendering HTML
SetCustomPaperSize (int width, int height)FunctionUsed to set custom paper size

ClassPdfHeaderFooter
DescriptionUsed to define PDF print out header and footer display options
Properties \ functionsTypeDescription
CenterTextstringSet the text in centered/left/right of PDF header or footer. Can also merge metadata using strings placeholders : {page} {totalpages}{url}{date}{time}{html-title}{pdf title}
LeftTextstring
RightTextstring
DrawDividerLineBooleanAdds a horizontal line divider between the header (text or HTML) and the page content on every page of the PDF document
FontFamilystringFont used to render PDF
FontSizeintFont size in px.
SpacingintSet the space between header/footer and page content in millimeters

7. Apply PDF Printing (Rendering) Options

Let us try to configure our PDF rendering options.

:path=/static-assets/pdf/content-code-examples/tutorials/dotnet-core-pdf-generating-12.cs
ChromePdfRenderer renderer = new ChromePdfRenderer();

// Set rendering options
renderer.RenderingOptions.PaperSize = IronPdf.Rendering.PdfPaperSize.A4;
renderer.RenderingOptions.PaperOrientation = IronPdf.Rendering.PdfPaperOrientation.Portrait;

renderer.RenderHtmlFileAsPdf(@"testFile.html").SaveAs("GeneratedFile.pdf");
Dim renderer As New ChromePdfRenderer()

' Set rendering options
renderer.RenderingOptions.PaperSize = IronPdf.Rendering.PdfPaperSize.A4
renderer.RenderingOptions.PaperOrientation = IronPdf.Rendering.PdfPaperOrientation.Portrait

renderer.RenderHtmlFileAsPdf("testFile.html").SaveAs("GeneratedFile.pdf")
VB   C#

8. Docker .NET Core Applications

8.1. What is Docker?

Docker is a set of platform as service products that uses OS-level virtualization to deliver software in packages called containers. Containers are isolated from one another and bundle their own software, libraries and configuration files; they can communicate with each other through well-defined channels.

You can learn more about Docker and ASP.NET Core application here.

We'll skip ahead to working with Docker, but if you want to learn more, there's a great introduction to .NET and Docker here. and even more about how to build containers for .NET core app.

Let's get started with Docker together.

8.2. Install Docker

Visit to the Docker website here to install Docker.

Click get started.

Click download for Mac and Windows.

Signup for free, then login.

Download Docker for Windows.

Start installing Docker.

It will require a restart. After your machine restartrs, login to Docker.

Now you can run Docker "hello world" by opening the Windows command line or PowerShell script and write:

Docker run hello-world

Here is a list of the most important command lines to help you:

  • Docker images => To list all available images on this machine
  • Docker ps => to list all running containers
  • Docker ps –a => to list all containers

8.3. Run into Linux container


9. Work with Existing PDF Documents

9.1. Open Existing PDF

As you can create a PDF from URL and HTML (text or file), you can also work with existing PDF documents.

The following is an example to open either a normal PDF or encrypted PDF with a password

:path=/static-assets/pdf/content-code-examples/tutorials/dotnet-core-pdf-generating-13.cs
// Open an unencrypted pdf
PdfDocument unencryptedPdf = PdfDocument.FromFile("testFile.pdf");

// Open an encrypted pdf
PdfDocument encryptedPdf = PdfDocument.FromFile("testFile2.pdf", "MyPassword");
' Open an unencrypted pdf
Dim unencryptedPdf As PdfDocument = PdfDocument.FromFile("testFile.pdf")

' Open an encrypted pdf
Dim encryptedPdf As PdfDocument = PdfDocument.FromFile("testFile2.pdf", "MyPassword")
VB   C#

9.2. Merge Multiple PDFs

You can merge multiple PDFs into one single PDF as follows:

:path=/static-assets/pdf/content-code-examples/tutorials/dotnet-core-pdf-generating-14.cs
List<PdfDocument> PDFs = new List<PdfDocument>();
PDFs.Add(PdfDocument.FromFile("1.pdf"));
PDFs.Add(PdfDocument.FromFile("2.pdf"));
PDFs.Add(PdfDocument.FromFile("3.pdf"));
using PdfDocument PDF = PdfDocument.Merge(PDFs);
PDF.SaveAs("mergedFile.pdf");
foreach (PdfDocument pdf in PDFs)
{
    pdf.Dispose();
}
Dim PDFs As New List(Of PdfDocument)()
PDFs.Add(PdfDocument.FromFile("1.pdf"))
PDFs.Add(PdfDocument.FromFile("2.pdf"))
PDFs.Add(PdfDocument.FromFile("3.pdf"))
Using PDF As PdfDocument = PdfDocument.Merge(PDFs)
	PDF.SaveAs("mergedFile.pdf")
'INSTANT VB NOTE: The variable pdf was renamed since Visual Basic will not allow local variables with the same name as parameters or other local variables:
	For Each Me.pdf_Conflict As PdfDocument In PDFs
		Me.pdf_Conflict.Dispose()
	Next pdf_Conflict
End Using
VB   C#

Append another PDF to the end of the current PDF as follows:

:path=/static-assets/pdf/content-code-examples/tutorials/dotnet-core-pdf-generating-15.cs
PdfDocument pdf = PdfDocument.FromFile("1.pdf");
PdfDocument pdf2 = PdfDocument.FromFile("2.pdf");
pdf.AppendPdf(pdf2);
pdf.SaveAs("appendedFile.pdf");
Dim pdf As PdfDocument = PdfDocument.FromFile("1.pdf")
Dim pdf2 As PdfDocument = PdfDocument.FromFile("2.pdf")
pdf.AppendPdf(pdf2)
pdf.SaveAs("appendedFile.pdf")
VB   C#

Insert a PDF into another PDF starting with given index:

:path=/static-assets/pdf/content-code-examples/tutorials/dotnet-core-pdf-generating-16.cs
PdfDocument pdf = PdfDocument.FromFile("1.pdf");
PdfDocument pdf2 = PdfDocument.FromFile("2.pdf");
pdf.InsertPdf(pdf2, 0);
pdf.SaveAs("InsertIntoSpecificIndex.pdf");
Dim pdf As PdfDocument = PdfDocument.FromFile("1.pdf")
Dim pdf2 As PdfDocument = PdfDocument.FromFile("2.pdf")
pdf.InsertPdf(pdf2, 0)
pdf.SaveAs("InsertIntoSpecificIndex.pdf")
VB   C#

9.3 Add Headers or Footers

You can add headers and footers to an existing PDF or when you render the PDF from HTML or URL.

There are two classes you can use to add header or footer to a PDF

  • SimpleHeaderFooter: this class to add simple text in header or footer.
  • HtmlHeaderFooter: this class to add header or footer with rich HTML content and images

Now let us see two examples of how to add header/footer to existing pdf or when it is rendered using these two classes

9.3.1 Add header to existing pdf Below is an example to load an existing PDF, then add a header and footer using AddHeaders() , AddFooters() methods

:path=/static-assets/pdf/content-code-examples/tutorials/dotnet-core-pdf-generating-17.cs
PdfDocument pdf = PdfDocument.FromFile("testFile.pdf");
TextHeaderFooter header = new TextHeaderFooter()
{
    CenterText = "Pdf Header",
    LeftText = "{date} {time}",
    RightText = "{page} of {total-pages}",
    DrawDividerLine = true,
    FontSize = 10
};
pdf.AddTextHeaders(header);
pdf.SaveAs("withHeader.pdf");

HtmlHeaderFooter Footer = new HtmlHeaderFooter()
{
    HtmlFragment = "<span style='text-align:right'> page {page} of {totalpages}</span>",
    DrawDividerLine = true,
    MaxHeight = 10 //mm
};
pdf.AddHtmlFooters(Footer);
pdf.SaveAs("withHeaderAndFooters.pdf");
Dim pdf As PdfDocument = PdfDocument.FromFile("testFile.pdf")
Dim header As New TextHeaderFooter() With {
	.CenterText = "Pdf Header",
	.LeftText = "{date} {time}",
	.RightText = "{page} of {total-pages}",
	.DrawDividerLine = True,
	.FontSize = 10
}
pdf.AddTextHeaders(header)
pdf.SaveAs("withHeader.pdf")

Dim Footer As New HtmlHeaderFooter() With {
	.HtmlFragment = "<span style='text-align:right'> page {page} of {totalpages}</span>",
	.DrawDividerLine = True,
	.MaxHeight = 10
}
pdf.AddHtmlFooters(Footer)
pdf.SaveAs("withHeaderAndFooters.pdf")
VB   C#

9.3.2 Add header and footer to new pdf Here is an example to create a PDF from HTML file and add a header and footer to it using print options

:path=/static-assets/pdf/content-code-examples/tutorials/dotnet-core-pdf-generating-18.cs
ChromePdfRenderer renderer = new ChromePdfRenderer();
renderer.RenderingOptions.TextHeader = new TextHeaderFooter()
{
    CenterText = "Pdf Header",
    LeftText = "{date} {time}",
    RightText = "{page} of {total-pages}",
    DrawDividerLine = true,
    FontSize = 10
};

renderer.RenderingOptions.HtmlFooter = new HtmlHeaderFooter()
{
    HtmlFragment = "<span style='text-align:right'> page {page} of {totalpages}</span>",
    DrawDividerLine = true,
    MaxHeight = 10
};
PdfDocument pdf = renderer.RenderHtmlFileAsPdf("test.html");
pdf.SaveAs("generatedFile.pdf");
Dim renderer As New ChromePdfRenderer()
renderer.RenderingOptions.TextHeader = New TextHeaderFooter() With {
	.CenterText = "Pdf Header",
	.LeftText = "{date} {time}",
	.RightText = "{page} of {total-pages}",
	.DrawDividerLine = True,
	.FontSize = 10
}

renderer.RenderingOptions.HtmlFooter = New HtmlHeaderFooter() With {
	.HtmlFragment = "<span style='text-align:right'> page {page} of {totalpages}</span>",
	.DrawDividerLine = True,
	.MaxHeight = 10
}
Dim pdf As PdfDocument = renderer.RenderHtmlFileAsPdf("test.html")
pdf.SaveAs("generatedFile.pdf")
VB   C#

10. Add PDF Password and Security

You can secure your PDF with a password and edit file security settings like prevent copying and printing.

:path=/static-assets/pdf/content-code-examples/tutorials/dotnet-core-pdf-generating-19.cs
PdfDocument pdf = PdfDocument.FromFile("testFile.pdf");

// Edit file metadata
pdf.MetaData.Author = "john smith";
pdf.MetaData.Keywords = "SEO, Friendly";
pdf.MetaData.ModifiedDate = DateTime.Now;

// Edit file security settings
// The following code makes a PDF read only and will disallow copy & paste and printing
pdf.SecuritySettings.RemovePasswordsAndEncryption();
pdf.SecuritySettings.MakePdfDocumentReadOnly("secret-key"); //secret-key is a owner password
pdf.SecuritySettings.AllowUserAnnotations = false;
pdf.SecuritySettings.AllowUserCopyPasteContent = false;
pdf.SecuritySettings.AllowUserFormData = false;
pdf.SecuritySettings.AllowUserPrinting = IronPdf.Security.PdfPrintSecurity.FullPrintRights;

// Change or set the document ecrpytion password
pdf.Password = "123";
pdf.SaveAs("secured.pdf");
Dim pdf As PdfDocument = PdfDocument.FromFile("testFile.pdf")

' Edit file metadata
pdf.MetaData.Author = "john smith"
pdf.MetaData.Keywords = "SEO, Friendly"
pdf.MetaData.ModifiedDate = DateTime.Now

' Edit file security settings
' The following code makes a PDF read only and will disallow copy & paste and printing
pdf.SecuritySettings.RemovePasswordsAndEncryption()
pdf.SecuritySettings.MakePdfDocumentReadOnly("secret-key") 'secret-key is a owner password
pdf.SecuritySettings.AllowUserAnnotations = False
pdf.SecuritySettings.AllowUserCopyPasteContent = False
pdf.SecuritySettings.AllowUserFormData = False
pdf.SecuritySettings.AllowUserPrinting = IronPdf.Security.PdfPrintSecurity.FullPrintRights

' Change or set the document ecrpytion password
pdf.Password = "123"
pdf.SaveAs("secured.pdf")
VB   C#

11. Digitally Sign PDFs

You can also digitally sign a PDF as follows:

:path=/static-assets/pdf/content-code-examples/tutorials/dotnet-core-pdf-generating-20.cs
PdfDocument pdf = PdfDocument.FromFile("testFile.pdf");
pdf.Sign(new PdfSignature("cert123.pfx", "password"), IronPdf.Signing.SignaturePermissions.Default);
pdf.SaveAs("signed.pdf");
Dim pdf As PdfDocument = PdfDocument.FromFile("testFile.pdf")
pdf.Sign(New PdfSignature("cert123.pfx", "password"), IronPdf.Signing.SignaturePermissions.Default)
pdf.SaveAs("signed.pdf")
VB   C#

Advanced example for more control:

:path=/static-assets/pdf/content-code-examples/tutorials/dotnet-core-pdf-generating-21.cs
PdfDocument pdf = PdfDocument.FromFile("testFile.pdf");
IronPdf.Signing.PdfSignature signature = new IronPdf.Signing.PdfSignature("cert123.pfx", "123");

// Optional signing options
signature.SigningContact = "support@ironsoftware.com";
signature.SigningLocation = "Chicago, USA";
signature.SigningReason = "To show how to sign a PDF";

// Sign the PDF with the PdfSignature. Multiple signing certificates may be used
pdf.Sign(signature);
Dim pdf As PdfDocument = PdfDocument.FromFile("testFile.pdf")
Dim signature As New IronPdf.Signing.PdfSignature("cert123.pfx", "123")

' Optional signing options
signature.SigningContact = "support@ironsoftware.com"
signature.SigningLocation = "Chicago, USA"
signature.SigningReason = "To show how to sign a PDF"

' Sign the PDF with the PdfSignature. Multiple signing certificates may be used
pdf.Sign(signature)
VB   C#

12. Extract Text and Images from PDF

Extract text and images

Using IronPdf you can extract text and images from a PDF as follows:

:path=/static-assets/pdf/content-code-examples/tutorials/dotnet-core-pdf-generating-22.cs
PdfDocument pdf = PdfDocument.FromFile("testFile.pdf");

pdf.ExtractAllText(); // Extract all text in the pdf
pdf.ExtractTextFromPage(0); // Read text from specific page

// Extract all images in the pdf
var AllImages = pdf.ExtractAllImages();

// Extract images from specific page
var ImagesOfAPage = pdf.ExtractImagesFromPage(0);
Dim pdf As PdfDocument = PdfDocument.FromFile("testFile.pdf")

pdf.ExtractAllText() ' Extract all text in the pdf
pdf.ExtractTextFromPage(0) ' Read text from specific page

' Extract all images in the pdf
Dim AllImages = pdf.ExtractAllImages()

' Extract images from specific page
Dim ImagesOfAPage = pdf.ExtractImagesFromPage(0)
VB   C#

12.1. Rasterize PDF to Image

You can also convert PDF pages to images as follows

:path=/static-assets/pdf/content-code-examples/tutorials/dotnet-core-pdf-generating-23.cs
PdfDocument pdf = PdfDocument.FromFile("testFile.pdf");

List<int> pageList = new List<int>() { 1, 2 };

pdf.RasterizeToImageFiles("*.png", pageList);
Dim pdf As PdfDocument = PdfDocument.FromFile("testFile.pdf")

Dim pageList As New List(Of Integer)() From {1, 2}

pdf.RasterizeToImageFiles("*.png", pageList)
VB   C#

13. Add PDF Watermark

The following is an example of how to watermark PDF pages using the watermarkAllPages() method

:path=/static-assets/pdf/content-code-examples/tutorials/dotnet-core-pdf-generating-24.cs
ChromePdfRenderer renderer = new ChromePdfRenderer();
PdfDocument pdf = renderer.RenderUrlAsPdf("https://www.nuget.org/packages/IronPdf");

// Apply watermark
pdf.ApplyWatermark("<h2 style='color:red'>SAMPLE</h2>", 30, IronPdf.Editing.VerticalAlignment.Middle, IronPdf.Editing.HorizontalAlignment.Center);
pdf.SaveAs("Watermarked.pdf");
Dim renderer As New ChromePdfRenderer()
Dim pdf As PdfDocument = renderer.RenderUrlAsPdf("https://www.nuget.org/packages/IronPdf")

' Apply watermark
pdf.ApplyWatermark("<h2 style='color:red'>SAMPLE</h2>", 30, IronPdf.Editing.VerticalAlignment.Middle, IronPdf.Editing.HorizontalAlignment.Center)
pdf.SaveAs("Watermarked.pdf")
VB   C#

Watermark is restricted to basic position and a 100mm by 100mm as a maximum size. For more control you can use StampHTML method:

:path=/static-assets/pdf/content-code-examples/tutorials/dotnet-core-pdf-generating-25.cs
ChromePdfRenderer renderer = new ChromePdfRenderer();
PdfDocument pdf = renderer.RenderHtmlAsPdf("<div>test text </div>");

// Configure HTML stamper
HtmlStamper backgroundStamp = new HtmlStamper()
{
    Html = "<h2 style='color:red'>copyright 2018 ironpdf.com",
    MaxWidth = new Length(20),
    MaxHeight = new Length(20),
    Opacity = 50,
    Rotation = -45,
    IsStampBehindContent = true,
    VerticalAlignment = VerticalAlignment.Middle
};

pdf.ApplyStamp(backgroundStamp);
pdf.SaveAs("stamped.pdf");
Dim renderer As New ChromePdfRenderer()
Dim pdf As PdfDocument = renderer.RenderHtmlAsPdf("<div>test text </div>")

' Configure HTML stamper
Dim backgroundStamp As New HtmlStamper() With {
	.Html = "<h2 style='color:red'>copyright 2018 ironpdf.com",
	.MaxWidth = New Length(20),
	.MaxHeight = New Length(20),
	.Opacity = 50,
	.Rotation = -45,
	.IsStampBehindContent = True,
	.VerticalAlignment = VerticalAlignment.Middle
}

pdf.ApplyStamp(backgroundStamp)
pdf.SaveAs("stamped.pdf")
VB   C#

Tutorial Quick Access

Get the Source Code

Access all the source code found in this tutorial as a Visual Studio project ZIP file, easy to use and share for your project.

Get the Code

GitHub Tutorial Access

Explore this tutorial and many more via GitHub. Using the projects and source code is the best way to learn and apply it to your own PDF .NET Core needs and use cases.

Generate PDFs in .NET Core Tutorial

Keep the PDF CSharp Cheat Sheet

Develop PDFS in your .NET applications using our handy reference document. Providing quick access to common functions and examples for generating and editing PDFs in C# and VB.NET, this shareable tool helps you save time and effort getting started with IronPDF and common PDF requirements in your project.

Keep the Cheat Sheet

More Documentation

Read the IronPDF API Reference, which thoroughly presents the details of all the features in IronPDF plus namespaces, classes, methods fields and enums.

API Reference Documentation