.NET Core PDF Generator

by Ahmed Aboelmagd

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 Core needs.

Render URL to PDF
static void Main(string[] args)
{
  Console.WriteLine("Hello World!");
  var render = new IronPdf.HtmlToPdf();
  var doc = render.RenderUrlAsPdf("https://www.wikipedia.org/");
  doc.SaveAs($@"{AppDomain.CurrentDomain.BaseDirectory}\wiki.pdf");
}
Shared Sub Main(ByVal args() As String)
  Console.WriteLine("Hello World!")
  Dim render = New IronPdf.HtmlToPdf()
  Dim doc = render.RenderUrlAsPdf("https://www.wikipedia.org/")
  doc.SaveAs($"{AppDomain.CurrentDomain.BaseDirectory}\wiki.pdf")
End Sub
Jump to Article
NET Core HTML to PDF
static void Main(string[] args)
{
  var render = new IronPdf.HtmlToPdf();
  var doc = render.RenderHtmlAsPdf("<h1>Hello IronPdf</h1>");
  doc.SaveAs($@"{AppDomain.CurrentDomain.BaseDirectory}\HtmlString.pdf");
}
Shared Sub Main(ByVal args() As String)
  Dim render = New IronPdf.HtmlToPdf()
  Dim doc = render.RenderHtmlAsPdf("<h1>Hello IronPdf</h1>")
  doc.SaveAs($"{AppDomain.CurrentDomain.BaseDirectory}\HtmlString.pdf")
End Sub
Jump to Article
MVC View to PDF
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
Jump to Article
MVC PDF Add Class
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
Jump to Article
MVC PDF Example
@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> }
Jump to Article
MVC PDF Add HTTPPost
[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
Jump to Article
MVC Partial View to String
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();
    }
  }
}
Public Module ControllerExtensions
'INSTANT VB TODO TASK: The following line could not be converted:
  public static async Task(Of String) RenderViewAsync(Of TModel)(Me Controller controller, String viewName, TModel model, Boolean partial = False)
  If True Then
	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 If
End Module
Jump to Article
PDF Print Option
var Renderer = new HtmlToPdf();

Renderer.PrintOptions= new PdfPrintOptions()
{
  DPI = 500,
  PaperSize = PdfPrintOptions.PdfPaperSize.A4,
  PaperOrientation = PdfPrintOptions.PdfPaperOrientation.Portrait,
  InputEncoding = System.Text.Encoding.UTF8
};

pdf.RenderHTMLFileAsPdf(@"testFile.html").SaveAs("GeneratedFile.pdf");
Dim Renderer = New HtmlToPdf()

Renderer.PrintOptions= New PdfPrintOptions() With {
	.DPI = 500,
	.PaperSize = PdfPrintOptions.PdfPaperSize.A4,
	.PaperOrientation = PdfPrintOptions.PdfPaperOrientation.Portrait,
	.InputEncoding = System.Text.Encoding.UTF8
}

pdf.RenderHTMLFileAsPdf("testFile.html").SaveAs("GeneratedFile.pdf")
Jump to Article
Open Existing PDF
var pdf = PdfDocument.FromFile(“testFile.pdf");
// to open an encrypted pdf
var pdf = PdfDocument.FromFile(“testFile2.pdf" ,"MyPassword");
Dim pdf = PdfDocument.FromFile("testFile.pdf")
' to open an encrypted pdf
Dim pdf = PdfDocument.FromFile("testFile2.pdf","MyPassword")
Jump to Article
Merge Multiple PDFs
var PDFs = new List<PdfDocument>();
PDFs.Add(PdfDocument.FromFile("1.pdf"));
PDFs.Add(PdfDocument.FromFile("2.pdf"));
PDFs.Add(PdfDocument.FromFile("3.pdf"));
PdfDocument PDF = PdfDocument.Merge(PDFs);
PDF.SaveAs("mergedFile.pdf");
Dim PDFs = New List(Of PdfDocument)()
PDFs.Add(PdfDocument.FromFile("1.pdf"))
PDFs.Add(PdfDocument.FromFile("2.pdf"))
PDFs.Add(PdfDocument.FromFile("3.pdf"))
Dim PDF As PdfDocument = PdfDocument.Merge(PDFs)
PDF.SaveAs("mergedFile.pdf")
Jump to Article
Add Page to PDF
var pdf = PdfDocument.FromFile("1.pdf");
var pdf2 = PdfDocument.FromFile("2.pdf");
pdf.AppendPdf(pdf2);
pdf.SaveAs("appendedFile.pdf");
Dim pdf = PdfDocument.FromFile("1.pdf")
Dim pdf2 = PdfDocument.FromFile("2.pdf")
pdf.AppendPdf(pdf2)
pdf.SaveAs("appendedFile.pdf")
Jump to Article
Add Headers Footers
var pdf = PdfDocument.FromFile("testFile.pdf");
var header = new SimpleHeaderFooter()
{
  CenterText="Pdf Header",
  LeftText= "{date} {time}",
  RightText ="{page} of {total-pages}",
  DrawDividerLine =true,
  FontSize=10
};
var Footer = new HtmlHeaderFooter()
{
  HtmlFragment= "<span style='text-align:right'> page {page} of {totalpages}</span>",
  DrawDividerLine=true,
  FontSize=15,
  Height=10
};

pdf.AddHeaders(header);
pdf.AddFooters(Footer);
pdf.SaveAs("withHeaderFooter.pdf");
Dim pdf = PdfDocument.FromFile("testFile.pdf")
Dim header = New SimpleHeaderFooter() With {
	.CenterText="Pdf Header",
	.LeftText= "{date} {time}",
	.RightText ="{page} of {total-pages}",
	.DrawDividerLine =True,
	.FontSize=10
}
Dim Footer = New HtmlHeaderFooter() With {
	.HtmlFragment= "<span style='text-align:right'> page {page} of {totalpages}</span>",
	.DrawDividerLine=True,
	.FontSize=15,
	.Height=10
}

pdf.AddHeaders(header)
pdf.AddFooters(Footer)
pdf.SaveAs("withHeaderFooter.pdf")
Jump to Article
Add Password Security
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 =
PdfDocument.PdfSecuritySettings.PdfPrintSecrity.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 = PdfDocument.PdfSecuritySettings.PdfPrintSecrity.FullPrintRights
'Change or set the document ecrpytion password
Pdf.Password = "123"
Pdf.SaveAs("secured.pdf")
Jump to Article
Digitally Sign PDF
PdfDocument Pdf = PdfDocument.FromFile("testFile.pdf");
Pdf.QuickSignPdfWithDigitalSignatureFile("cert123.pfx", "123");
Pdf.SaveAs("signed.pdf");
Dim Pdf As PdfDocument = PdfDocument.FromFile("testFile.pdf")
Pdf.QuickSignPdfWithDigitalSignatureFile("cert123.pfx", "123")
Pdf.SaveAs("signed.pdf")
Jump to Article
Advanced Digitally Sign
PdfDocument Pdf = PdfDocument.FromFile("testFile.pdf");
var signature = new IronPdf.PdfSignature("cert123.pfx", "123");
//Optional signing options and a handwritten signature graphic
signature.SigningContact = "support@ironsoftware.com";
signature.SigningLocation = "Chicago, USA";
signature.SigningReason = "To show how to sign a PDF";
signature.LoadSignatureImageFromFile("handwriting.jpg");
//Sign the PDF with the PdfSignature. Multiple signing certificates may be used
Pdf.SignPdfWithDigitalSignature(
Dim Pdf As PdfDocument = PdfDocument.FromFile("testFile.pdf")
Dim signature = New IronPdf.PdfSignature("cert123.pfx", "123")
'Optional signing options and a handwritten signature graphic
signature.SigningContact = "support@ironsoftware.com"
signature.SigningLocation = "Chicago, USA"
signature.SigningReason = "To show how to sign a PDF"
signature.LoadSignatureImageFromFile("handwriting.jpg")
'Sign the PDF with the PdfSignature. Multiple signing certificates may be used
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'Pdf.SignPdfWithDigitalSignature(
Jump to Article
Extract Text and Images
PdfDocument Pdf = PdfDocument.FromFile("testFile.pdf");
Pdf.ExtractAllText(); //to extract all text in the pdf
Pdf.ExtractTextFromPage(0); //to read text from specific page
//to extract all images in the pdf
IEnumerable<System.Drawing.Image> AllImages = Pdf.ExtractAllImages();
//to extract images from specific page
IEnumerable<System.Drawing.Image> ImagesOfAPage= Pdf.ExtractImagesFromPage(0);
Dim Pdf As PdfDocument = PdfDocument.FromFile("testFile.pdf")
Pdf.ExtractAllText() 'to extract all text in the pdf
Pdf.ExtractTextFromPage(0) 'to read text from specific page
'to extract all images in the pdf
Dim AllImages As IEnumerable(Of System.Drawing.Image) = Pdf.ExtractAllImages()
'to extract images from specific page
Dim ImagesOfAPage As IEnumerable(Of System.Drawing.Image)= Pdf.ExtractImagesFromPage(0)
Jump to Article
Rasterize PDF to Image
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)
Jump to Article
Add Watermark
IronPdf.HtmlToPdf Renderer = new IronPdf.HtmlToPdf();
var pdf = Renderer.RenderUrlAsPdf("https://www.nuget.org/packages/IronPdf");
pdf.WatermarkAllPages("<h2 style='color:red'>SAMPLE</h2>",
PdfDocument.WaterMarkLocation.MiddleCenter, 50, -45, "https://www.nuget.org/packages/IronPdf");
pdf.SaveAs("Watermarked.pdf");
Dim Renderer As New IronPdf.HtmlToPdf()
Dim pdf = Renderer.RenderUrlAsPdf("https://www.nuget.org/packages/IronPdf")
pdf.WatermarkAllPages("<h2 style='color:red'>SAMPLE</h2>", PdfDocument.WaterMarkLocation.MiddleCenter, 50, -45, "https://www.nuget.org/packages/IronPdf")
pdf.SaveAs("Watermarked.pdf")
Jump to Article
Try IronPDF free for development


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# PDF DLL

Download DLL

Download DLL

Manually install into your project

or
C# Nuget Library for PDF

Install with NuGet

Install-Package IronPdf

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

static void Main(string[] args)
{
  Console.WriteLine("Hello World!");
  var render = new IronPdf.HtmlToPdf();
  var doc = render.RenderUrlAsPdf("https://www.wikipedia.org/");
  doc.SaveAs($@"{AppDomain.CurrentDomain.BaseDirectory}\wiki.pdf");
}
static void Main(string[] args)
{
  Console.WriteLine("Hello World!");
  var render = new IronPdf.HtmlToPdf();
  var doc = render.RenderUrlAsPdf("https://www.wikipedia.org/");
  doc.SaveAs($@"{AppDomain.CurrentDomain.BaseDirectory}\wiki.pdf");
}
Shared Sub Main(ByVal args() As String)
  Console.WriteLine("Hello World!")
  Dim render = New IronPdf.HtmlToPdf()
  Dim doc = render.RenderUrlAsPdf("https://www.wikipedia.org/")
  doc.SaveAs($"{AppDomain.CurrentDomain.BaseDirectory}\wiki.pdf")
End Sub
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.

static void Main(string[] args)
{
  var render = new IronPdf.HtmlToPdf();
  var doc = render.RenderHtmlAsPdf("<h1>Hello IronPdf</h1>");
  doc.SaveAs($@"{AppDomain.CurrentDomain.BaseDirectory}\HtmlString.pdf");
}
static void Main(string[] args)
{
  var render = new IronPdf.HtmlToPdf();
  var doc = render.RenderHtmlAsPdf("<h1>Hello IronPdf</h1>");
  doc.SaveAs($@"{AppDomain.CurrentDomain.BaseDirectory}\HtmlString.pdf");
}
Shared Sub Main(ByVal args() As String)
  Dim render = New IronPdf.HtmlToPdf()
  Dim doc = render.RenderHtmlAsPdf("<h1>Hello IronPdf</h1>")
  doc.SaveAs($"{AppDomain.CurrentDomain.BaseDirectory}\HtmlString.pdf")
End Sub
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

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

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

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

[HttpPost]
public ActionResult Index(ClientModel model)
{
  if (ModelState.IsValid)
  {
    ClientServices.AddClient(model);
    Return RedirectToAction("TicketView");
  }
  return View(model);
}
[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

public ActionResult TicketView()
{
  var ticket = ClientServices.GetClient();
  return View(ticket);
}
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

public class TicketModel : ClientModel
{
  public int TicketNumber { get; set; }
  public DateTime TicketDate { get; set; }
}
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

[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.HtmlToPdf();
  var pdfDoc = ironPdfRender.RenderHtmlAsPdf(html.Result);
  return File(pdfDoc.Stream.ToArray(), "application/pdf");
}
[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.HtmlToPdf();
  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.HtmlToPdf()
  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

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();
    }
  }
}
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();
    }
  }
}
Public Module ControllerExtensions
'INSTANT VB TODO TASK: The following line could not be converted:
  public static async Task(Of String) RenderViewAsync(Of TModel)(Me Controller controller, String viewName, TModel model, Boolean partial = False)
  If True Then
	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 If
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.

ClassPdfPrintOptions
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
FooterPdfHeaderFooterSet the footer content see Header PdfHeaderFooter Class
Header
GrayScaleBooleanOutput PDF in black and white scale
InputEncodingSystem.Text.EncodingDefine input character encoding
jpegQualityintQuality of images, take values from 0 to 100
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 PDFPrintOption

Let us try to use PdfPrintOption

var Renderer = new HtmlToPdf();

Renderer.PrintOptions= new PdfPrintOptions()
{
  DPI = 500,
  PaperSize = PdfPrintOptions.PdfPaperSize.A4,
  PaperOrientation = PdfPrintOptions.PdfPaperOrientation.Portrait,
  InputEncoding = System.Text.Encoding.UTF8
};

pdf.RenderHTMLFileAsPdf(@"testFile.html").SaveAs("GeneratedFile.pdf");
var Renderer = new HtmlToPdf();

Renderer.PrintOptions= new PdfPrintOptions()
{
  DPI = 500,
  PaperSize = PdfPrintOptions.PdfPaperSize.A4,
  PaperOrientation = PdfPrintOptions.PdfPaperOrientation.Portrait,
  InputEncoding = System.Text.Encoding.UTF8
};

pdf.RenderHTMLFileAsPdf(@"testFile.html").SaveAs("GeneratedFile.pdf");
Dim Renderer = New HtmlToPdf()

Renderer.PrintOptions= New PdfPrintOptions() With {
	.DPI = 500,
	.PaperSize = PdfPrintOptions.PdfPaperSize.A4,
	.PaperOrientation = PdfPrintOptions.PdfPaperOrientation.Portrait,
	.InputEncoding = System.Text.Encoding.UTF8
}

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

var pdf = PdfDocument.FromFile(“testFile.pdf");
// to open an encrypted pdf
var pdf = PdfDocument.FromFile(“testFile2.pdf" ,"MyPassword");
var pdf = PdfDocument.FromFile(“testFile.pdf");
// to open an encrypted pdf
var pdf = PdfDocument.FromFile(“testFile2.pdf" ,"MyPassword");
Dim pdf = PdfDocument.FromFile("testFile.pdf")
' to open an encrypted pdf
Dim pdf = PdfDocument.FromFile("testFile2.pdf","MyPassword")
VB   C#

9.2. Merge Multiple PDFs

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

var PDFs = new List<PdfDocument>();
PDFs.Add(PdfDocument.FromFile("1.pdf"));
PDFs.Add(PdfDocument.FromFile("2.pdf"));
PDFs.Add(PdfDocument.FromFile("3.pdf"));
PdfDocument PDF = PdfDocument.Merge(PDFs);
PDF.SaveAs("mergedFile.pdf");
var PDFs = new List<PdfDocument>();
PDFs.Add(PdfDocument.FromFile("1.pdf"));
PDFs.Add(PdfDocument.FromFile("2.pdf"));
PDFs.Add(PdfDocument.FromFile("3.pdf"));
PdfDocument PDF = PdfDocument.Merge(PDFs);
PDF.SaveAs("mergedFile.pdf");
Dim PDFs = New List(Of PdfDocument)()
PDFs.Add(PdfDocument.FromFile("1.pdf"))
PDFs.Add(PdfDocument.FromFile("2.pdf"))
PDFs.Add(PdfDocument.FromFile("3.pdf"))
Dim PDF As PdfDocument = PdfDocument.Merge(PDFs)
PDF.SaveAs("mergedFile.pdf")
VB   C#

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

var pdf = PdfDocument.FromFile("1.pdf");
var pdf2 = PdfDocument.FromFile("2.pdf");
pdf.AppendPdf(pdf2);
pdf.SaveAs("appendedFile.pdf");
var pdf = PdfDocument.FromFile("1.pdf");
var pdf2 = PdfDocument.FromFile("2.pdf");
pdf.AppendPdf(pdf2);
pdf.SaveAs("appendedFile.pdf");
Dim pdf = PdfDocument.FromFile("1.pdf")
Dim pdf2 = PdfDocument.FromFile("2.pdf")
pdf.AppendPdf(pdf2)
pdf.SaveAs("appendedFile.pdf")
VB   C#

Insert a PDF into another PDF starting with given index

var pdf = PdfDocument.FromFile("1.pdf");
var pdf2 = PdfDocument.FromFile("2.pdf");
pdf.InsertPdf(pdf2, 0);
pdf.SaveAs("InsertIntoSpecificIndex.pdf");
var pdf = PdfDocument.FromFile("1.pdf");
var pdf2 = PdfDocument.FromFile("2.pdf");
pdf.InsertPdf(pdf2, 0);
pdf.SaveAs("InsertIntoSpecificIndex.pdf");
Dim pdf = PdfDocument.FromFile("1.pdf")
Dim pdf2 = 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

var pdf = PdfDocument.FromFile("testFile.pdf");
var header = new SimpleHeaderFooter()
{
  CenterText="Pdf Header",
  LeftText= "{date} {time}",
  RightText ="{page} of {total-pages}",
  DrawDividerLine =true,
  FontSize=10
};
var Footer = new HtmlHeaderFooter()
{
  HtmlFragment= "<span style='text-align:right'> page {page} of {totalpages}</span>",
  DrawDividerLine=true,
  FontSize=15,
  Height=10
};

pdf.AddHeaders(header);
pdf.AddFooters(Footer);
pdf.SaveAs("withHeaderFooter.pdf");
var pdf = PdfDocument.FromFile("testFile.pdf");
var header = new SimpleHeaderFooter()
{
  CenterText="Pdf Header",
  LeftText= "{date} {time}",
  RightText ="{page} of {total-pages}",
  DrawDividerLine =true,
  FontSize=10
};
var Footer = new HtmlHeaderFooter()
{
  HtmlFragment= "<span style='text-align:right'> page {page} of {totalpages}</span>",
  DrawDividerLine=true,
  FontSize=15,
  Height=10
};

pdf.AddHeaders(header);
pdf.AddFooters(Footer);
pdf.SaveAs("withHeaderFooter.pdf");
Dim pdf = PdfDocument.FromFile("testFile.pdf")
Dim header = New SimpleHeaderFooter() With {
	.CenterText="Pdf Header",
	.LeftText= "{date} {time}",
	.RightText ="{page} of {total-pages}",
	.DrawDividerLine =True,
	.FontSize=10
}
Dim Footer = New HtmlHeaderFooter() With {
	.HtmlFragment= "<span style='text-align:right'> page {page} of {totalpages}</span>",
	.DrawDividerLine=True,
	.FontSize=15,
	.Height=10
}

pdf.AddHeaders(header)
pdf.AddFooters(Footer)
pdf.SaveAs("withHeaderFooter.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

var renderer = new HtmlToPdf();
renderer.PrintOptions.Header= new SimpleHeaderFooter()
{
  CenterText="Pdf Header",
  LeftText= "{date} {time}",
  RightText ="{page} of {total-pages}",
  DrawDividerLine =true,
  FontSize=10
};
renderer.PrintOptions.Footer = new HtmlHeaderFooter()
{
  HtmlFragment= "<span style='text-align:right'> page {page} of {totalpages}</span>",
  DrawDividerLine=true,
  FontSize=15,
  Height=10
};
var pdf = renderer.RenderHTMLFileAsPdf("test.html");
pdf.SaveAs("generatedFile.pdf");
var renderer = new HtmlToPdf();
renderer.PrintOptions.Header= new SimpleHeaderFooter()
{
  CenterText="Pdf Header",
  LeftText= "{date} {time}",
  RightText ="{page} of {total-pages}",
  DrawDividerLine =true,
  FontSize=10
};
renderer.PrintOptions.Footer = new HtmlHeaderFooter()
{
  HtmlFragment= "<span style='text-align:right'> page {page} of {totalpages}</span>",
  DrawDividerLine=true,
  FontSize=15,
  Height=10
};
var pdf = renderer.RenderHTMLFileAsPdf("test.html");
pdf.SaveAs("generatedFile.pdf");
Dim renderer = New HtmlToPdf()
renderer.PrintOptions.Header= New SimpleHeaderFooter() With {
	.CenterText="Pdf Header",
	.LeftText= "{date} {time}",
	.RightText ="{page} of {total-pages}",
	.DrawDividerLine =True,
	.FontSize=10
}
renderer.PrintOptions.Footer = New HtmlHeaderFooter() With {
	.HtmlFragment= "<span style='text-align:right'> page {page} of {totalpages}</span>",
	.DrawDividerLine=True,
	.FontSize=15,
	.Height=10
}
Dim pdf = 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.

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 =
PdfDocument.PdfSecuritySettings.PdfPrintSecrity.FullPrintRights;
//Change or set the document ecrpytion password
Pdf.Password = "123";
Pdf.SaveAs("secured.pdf");
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 =
PdfDocument.PdfSecuritySettings.PdfPrintSecrity.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 = PdfDocument.PdfSecuritySettings.PdfPrintSecrity.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:

PdfDocument Pdf = PdfDocument.FromFile("testFile.pdf");
Pdf.QuickSignPdfWithDigitalSignatureFile("cert123.pfx", "123");
Pdf.SaveAs("signed.pdf");
PdfDocument Pdf = PdfDocument.FromFile("testFile.pdf");
Pdf.QuickSignPdfWithDigitalSignatureFile("cert123.pfx", "123");
Pdf.SaveAs("signed.pdf");
Dim Pdf As PdfDocument = PdfDocument.FromFile("testFile.pdf")
Pdf.QuickSignPdfWithDigitalSignatureFile("cert123.pfx", "123")
Pdf.SaveAs("signed.pdf")
VB   C#

Advanced example for more control:

PdfDocument Pdf = PdfDocument.FromFile("testFile.pdf");
var signature = new IronPdf.PdfSignature("cert123.pfx", "123");
//Optional signing options and a handwritten signature graphic
signature.SigningContact = "support@ironsoftware.com";
signature.SigningLocation = "Chicago, USA";
signature.SigningReason = "To show how to sign a PDF";
signature.LoadSignatureImageFromFile("handwriting.jpg");
//Sign the PDF with the PdfSignature. Multiple signing certificates may be used
Pdf.SignPdfWithDigitalSignature(
PdfDocument Pdf = PdfDocument.FromFile("testFile.pdf");
var signature = new IronPdf.PdfSignature("cert123.pfx", "123");
//Optional signing options and a handwritten signature graphic
signature.SigningContact = "support@ironsoftware.com";
signature.SigningLocation = "Chicago, USA";
signature.SigningReason = "To show how to sign a PDF";
signature.LoadSignatureImageFromFile("handwriting.jpg");
//Sign the PDF with the PdfSignature. Multiple signing certificates may be used
Pdf.SignPdfWithDigitalSignature(
Dim Pdf As PdfDocument = PdfDocument.FromFile("testFile.pdf")
Dim signature = New IronPdf.PdfSignature("cert123.pfx", "123")
'Optional signing options and a handwritten signature graphic
signature.SigningContact = "support@ironsoftware.com"
signature.SigningLocation = "Chicago, USA"
signature.SigningReason = "To show how to sign a PDF"
signature.LoadSignatureImageFromFile("handwriting.jpg")
'Sign the PDF with the PdfSignature. Multiple signing certificates may be used
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'Pdf.SignPdfWithDigitalSignature(
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:

PdfDocument Pdf = PdfDocument.FromFile("testFile.pdf");
Pdf.ExtractAllText(); //to extract all text in the pdf
Pdf.ExtractTextFromPage(0); //to read text from specific page
//to extract all images in the pdf
IEnumerable<System.Drawing.Image> AllImages = Pdf.ExtractAllImages();
//to extract images from specific page
IEnumerable<System.Drawing.Image> ImagesOfAPage= Pdf.ExtractImagesFromPage(0);
PdfDocument Pdf = PdfDocument.FromFile("testFile.pdf");
Pdf.ExtractAllText(); //to extract all text in the pdf
Pdf.ExtractTextFromPage(0); //to read text from specific page
//to extract all images in the pdf
IEnumerable<System.Drawing.Image> AllImages = Pdf.ExtractAllImages();
//to extract images from specific page
IEnumerable<System.Drawing.Image> ImagesOfAPage= Pdf.ExtractImagesFromPage(0);
Dim Pdf As PdfDocument = PdfDocument.FromFile("testFile.pdf")
Pdf.ExtractAllText() 'to extract all text in the pdf
Pdf.ExtractTextFromPage(0) 'to read text from specific page
'to extract all images in the pdf
Dim AllImages As IEnumerable(Of System.Drawing.Image) = Pdf.ExtractAllImages()
'to extract images from specific page
Dim ImagesOfAPage As IEnumerable(Of System.Drawing.Image)= Pdf.ExtractImagesFromPage(0)
VB   C#

12.1. Rasterize PDF to Image

You can also convert pdf pages to images as follows

PdfDocument Pdf = PdfDocument.FromFile("testFile.pdf");
List<int> pageList = new List<int>() { 1,2};
Pdf.RasterizeToImageFiles("*.png", pageList);
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

IronPdf.HtmlToPdf Renderer = new IronPdf.HtmlToPdf();
var pdf = Renderer.RenderUrlAsPdf("https://www.nuget.org/packages/IronPdf");
pdf.WatermarkAllPages("<h2 style='color:red'>SAMPLE</h2>",
PdfDocument.WaterMarkLocation.MiddleCenter, 50, -45, "https://www.nuget.org/packages/IronPdf");
pdf.SaveAs("Watermarked.pdf");
IronPdf.HtmlToPdf Renderer = new IronPdf.HtmlToPdf();
var pdf = Renderer.RenderUrlAsPdf("https://www.nuget.org/packages/IronPdf");
pdf.WatermarkAllPages("<h2 style='color:red'>SAMPLE</h2>",
PdfDocument.WaterMarkLocation.MiddleCenter, 50, -45, "https://www.nuget.org/packages/IronPdf");
pdf.SaveAs("Watermarked.pdf");
Dim Renderer As New IronPdf.HtmlToPdf()
Dim pdf = Renderer.RenderUrlAsPdf("https://www.nuget.org/packages/IronPdf")
pdf.WatermarkAllPages("<h2 style='color:red'>SAMPLE</h2>", PdfDocument.WaterMarkLocation.MiddleCenter, 50, -45, "https://www.nuget.org/packages/IronPdf")
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:

IronPdf.HtmlToPdf Renderer = new IronPdf.HtmlToPdf();
var pdf = Renderer.RenderHtmlAsPdf("<div>test text </div>");
var backgroundStamp = new HtmlStamp() { Html = "<h2 style='color:red'>copyright 2018 ironpdf.com", Width = 100, Height = 100, Opacity = 50, Rotation = -45, ZIndex = HtmlStamp.StampLayer.BehindExistingPDFContent Location=PdfDocument.WaterMarkLocation.MiddleCenter
};
pdf.StampHTML(backgroundStamp);
pdf.SaveAs("stamped.pdf");
IronPdf.HtmlToPdf Renderer = new IronPdf.HtmlToPdf();
var pdf = Renderer.RenderHtmlAsPdf("<div>test text </div>");
var backgroundStamp = new HtmlStamp() { Html = "<h2 style='color:red'>copyright 2018 ironpdf.com", Width = 100, Height = 100, Opacity = 50, Rotation = -45, ZIndex = HtmlStamp.StampLayer.BehindExistingPDFContent Location=PdfDocument.WaterMarkLocation.MiddleCenter
};
pdf.StampHTML(backgroundStamp);
pdf.SaveAs("stamped.pdf");
Dim Renderer As New IronPdf.HtmlToPdf()
Dim pdf = Renderer.RenderHtmlAsPdf("<div>test text </div>")
Dim backgroundStamp = New HtmlStamp() With {
	.Html = "<h2 style='color:red'>copyright 2018 ironpdf.com",
	.Width = 100,
	.Height = 100,
	.Opacity = 50,
	.Rotation = -45,
	.ZIndex = HtmlStamp.StampLayer.BehindExistingPDFContent Location=PdfDocument.WaterMarkLocation.MiddleCenter
}
pdf.StampHTML(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 Object Reference, which thoroughly presents the details of all the features in IronPDF plus namespaces, classes, methods fields and enums.

Object Reference Documentation

Ahmed Aboelmagd

.Net Software Solution Architect at an Multinational IT Company

Ahmed Aboelmagd is a Full-stack experienced and certified Microsoft technology specialist with 12+ years’ experience in IT and Software development, delivered 15+ successful project in many size scales from small to an enterprise for industries like (tourism, educational, manufacturing, etc.)