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.
How to Generate PDF Files in .NET Core
- Download .NET Core PDF Generator Library
- Convert .NET core HTML or MVC view to PDF
- Choose Render Options
- Add PDF Password or Digitally Sign
- Extract text images or add watermark
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.
1. Install the IronPDF Library Free
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
C#:
/**
Render URL to PDF
anchor-convert-website-to-pdf
**/
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
var render = new IronPdf.ChromePdfRenderer();
var doc = render.RenderUrlAsPdf("https://www.wikipedia.org/");
doc.SaveAs("wiki.pdf");
}
VB:
'''
'''Render URL to PDF
'''anchor-convert-website-to-pdf
'''*
Shared Sub Main(ByVal args() As String)
Console.WriteLine("Hello World!")
Dim render = New IronPdf.ChromePdfRenderer()
Dim doc = render.RenderUrlAsPdf("https://www.wikipedia.org/")
doc.SaveAs("wiki.pdf")
End Sub
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.
C#:
/**
NET Core HTML to PDF
anchor-convert-net-core-html-to-pdf
**/
static void Main(string[] args)
{
var render = new IronPdf.ChromePdfRenderer();
var doc = render.RenderHtmlAsPdf("<h1>Hello IronPdf</h1>");
doc.SaveAs("HtmlString.pdf");
}
VB:
'''
'''NET Core HTML to PDF
'''anchor-convert-net-core-html-to-pdf
'''*
Shared Sub Main(ByVal args() As String)
Dim render = New IronPdf.ChromePdfRenderer()
Dim doc = render.RenderHtmlAsPdf("<h1>Hello IronPdf</h1>")
doc.SaveAs("HtmlString.pdf")
End Sub
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
C#:
/**
MVC View to PDF
anchor-convert-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; }
}
VB:
'''
'''MVC View to PDF
'''anchor-convert-mvc-view-to-pdf
'''*
Public Class ClientModel
<Required>
Public Property Name() As String
<Required>
Public Property Phone() As String
<Required>
Public Property Email() As String
End Class
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
C#:
/**
MVC PDF Add Class
anchor-convert-mvc-view-to-pdf
**/
public class ClientServices
{
private static ClientModel _clientModel;
public static void AddClient(ClientModel clientModel)
{
_clientModel = clientModel;
}
public static ClientModel GetClient()
{
return _clientModel;
}
}
VB:
'''
'''MVC PDF Add Class
'''anchor-convert-mvc-view-to-pdf
'''*
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
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
C#:
/**
MVC PDF Example
anchor-convert-mvc-view-to-pdf
**/
@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>
}
VB:
'''
'''MVC PDF Example
'''anchor-convert-mvc-view-to-pdf
'''*
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> }
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>
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.
C#:
/**
MVC PDF Add HTTPPost
anchor-convert-mvc-view-to-pdf
**/
[HttpPost]
public ActionResult Index(ClientModel model)
{
if (ModelState.IsValid)
{
ClientServices.AddClient(model);
Return RedirectToAction("TicketView");
}
return View(model);
}
VB:
'''
'''MVC PDF Add HTTPPost
'''anchor-convert-mvc-view-to-pdf
'''*
<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
Sample of error messages
22- Add TicketView to display our ticket
C#:
public ActionResult TicketView()
{
var ticket = ClientServices.GetClient();
return View(ticket);
}
VB:
Public Function TicketView() As ActionResult
Dim ticket = ClientServices.GetClient()
Return View(ticket)
End Function
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
C#:
public class TicketModel : ClientModel
{
public int TicketNumber { get; set; }
public DateTime TicketDate { get; set; }
}
VB:
Public Class TicketModel
Inherits ClientModel
Public Property TicketNumber() As Integer
Public Property TicketDate() As DateTime
End Class
27- Add IronPDF to project
28- Click OK
29- Add the TicketView post method that will handle the download button
C#:
[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();
var pdfDoc = ironPdfRender.RenderHtmlAsPdf(html.Result);
return File(pdfDoc.Stream.ToArray(), "application/pdf");
}
VB:
<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
30- Add the controller extension that will render partial view to string
31- Use the Extension code as follows
C#:
/**
MVC Partial View to String
anchor-convert-mvc-view-to-pdf
**/
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();
}
}
}
VB:
'''
'''MVC Partial View to String
'''anchor-convert-mvc-view-to-pdf
'''*
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
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.
6. .NET PDF Header Footer Options Chart
7. Apply PDF Printing (Rendering) Options
Let us try to configure our PDF rendering options
C#:
/**
PDF Print Option
anchor-apply-pdfprintoption
**/
var Renderer = new ChromePdfRenderer();
Renderer.RenderingOptions.PaperSize = IronPdf.Rendering.PdfPaperSize.A4;
Renderer.RenderingOptions.PaperOrientation = IronPdf.Rendering.PdfPaperOrientation.Portrait;
pdf.RenderHTMLFileAsPdf(@"testFile.html").SaveAs("GeneratedFile.pdf");
VB:
'''
'''PDF Print Option
'''anchor-apply-pdfprintoption
'''*
Dim Renderer = New ChromePdfRenderer()
Renderer.RenderingOptions.PaperSize = IronPdf.Rendering.PdfPaperSize.A4
Renderer.RenderingOptions.PaperOrientation = IronPdf.Rendering.PdfPaperOrientation.Portrait
pdf.RenderHTMLFileAsPdf("testFile.html").SaveAs("GeneratedFile.pdf")
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.
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 restarts, 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
C#:
/**
Open Existing PDF
anchor-work-with-existing-pdf-documents
**/
var pdf = PdfDocument.FromFile(“testFile.pdf");
// to open an encrypted pdf
var pdf = PdfDocument.FromFile(“testFile2.pdf" ,"MyPassword");
VB:
'''
'''Open Existing PDF
'''anchor-work-with-existing-pdf-documents
'''*
Dim pdf = PdfDocument.FromFile("testFile.pdf")
' to open an encrypted pdf
Dim pdf = PdfDocument.FromFile("testFile2.pdf","MyPassword")
9.2 Merge Multiple PDFs
You can merge multiple PDFs into one single PDF as follows:
C#:
/**
Merge Multiple PDFs
anchor-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");
VB:
'''
'''Merge Multiple PDFs
'''anchor-merge-multiple-pdfs
'''*
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")
Append another PDF to the end of the current PDF as follows:
C#:
/**
Add Page to PDF
anchor-merge-multiple-pdfs
**/
var pdf = PdfDocument.FromFile("1.pdf");
var pdf2 = PdfDocument.FromFile("2.pdf");
pdf.AppendPdf(pdf2);
pdf.SaveAs("appendedFile.pdf");
VB:
'''
'''Add Page to PDF
'''anchor-merge-multiple-pdfs
'''*
Dim pdf = PdfDocument.FromFile("1.pdf")
Dim pdf2 = PdfDocument.FromFile("2.pdf")
pdf.AppendPdf(pdf2)
pdf.SaveAs("appendedFile.pdf")
Insert a PDF into another PDF starting with given index
C#:
var pdf = PdfDocument.FromFile("1.pdf");
var pdf2 = PdfDocument.FromFile("2.pdf");
pdf.InsertPdf(pdf2, 0);
pdf.SaveAs("InsertIntoSpecificIndex.pdf");
VB:
Dim pdf = PdfDocument.FromFile("1.pdf")
Dim pdf2 = PdfDocument.FromFile("2.pdf")
pdf.InsertPdf(pdf2, 0)
pdf.SaveAs("InsertIntoSpecificIndex.pdf")
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
C#:
/**
Add Headers Footers
anchor-add-headers-or-footers
**/
var pdf = PdfDocument.FromFile("testFile.pdf");
var header = new TextHeaderFooter()
{
CenterText="Pdf Header",
LeftText= "{date} {time}",
RightText ="{page} of {total-pages}",
DrawDividerLine =true,
FontSize=10
};
pdf.AddHeaders(header);
pdf.SaveAs("withHeader.pdf");
var Footer = new HtmlHeaderFooter()
{
HtmlFragment= "<span style='text-align:right'> page {page} of {totalpages}</span>",
DrawDividerLine=true,
FontSize=15,
MaxHeight=10 //mm
};
pdf.AddFooters(Footer);
pdf.SaveAs("withHeaderAndFooters.pdf");
VB:
'''
'''Add Headers Footers
'''anchor-add-headers-or-footers
'''*
Dim pdf = PdfDocument.FromFile("testFile.pdf")
Dim header = New TextHeaderFooter() With {
.CenterText="Pdf Header",
.LeftText= "{date} {time}",
.RightText ="{page} of {total-pages}",
.DrawDividerLine =True,
.FontSize=10
}
pdf.AddHeaders(header)
pdf.SaveAs("withHeader.pdf")
Dim Footer = New HtmlHeaderFooter() With {
.HtmlFragment= "<span style='text-align:right'> page {page} of {totalpages}</span>",
.DrawDividerLine=True,
.FontSize=15,
.MaxHeight=10
}
pdf.AddFooters(Footer)
pdf.SaveAs("withHeaderAndFooters.pdf")
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
C#:
var renderer = new ChromePdfRenderer();
renderer.RenderingOptions.Header= new TextHeaderFooter()
{
CenterText="Pdf Header",
LeftText= "{date} {time}",
RightText ="{page} of {total-pages}",
DrawDividerLine =true,
FontSize=10
};
renderer.RenderingOptions.Footer = new HtmlHeaderFooter()
{
HtmlFragment= "<span style='text-align:right'> page {page} of {totalpages}</span>",
DrawDividerLine=true,
FontSize=15,
MaxHeight=10
};
var pdf = renderer.RenderHTMLFileAsPdf("test.html");
pdf.SaveAs("generatedFile.pdf");
VB:
Dim renderer = New ChromePdfRenderer()
renderer.RenderingOptions.Header= New TextHeaderFooter() With {
.CenterText="Pdf Header",
.LeftText= "{date} {time}",
.RightText ="{page} of {total-pages}",
.DrawDividerLine =True,
.FontSize=10
}
renderer.RenderingOptions.Footer = New HtmlHeaderFooter() With {
.HtmlFragment= "<span style='text-align:right'> page {page} of {totalpages}</span>",
.DrawDividerLine=True,
.FontSize=15,
.MaxHeight=10
}
Dim pdf = renderer.RenderHTMLFileAsPdf("test.html")
pdf.SaveAs("generatedFile.pdf")
10. Add PDF Password and Security
You can secure your PDF with a password and edit file security settings like prevent copying and printing.
C#:
/**
Add Password Security
anchor-add-pdf-password-and-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");
VB:
'''
'''Add Password Security
'''anchor-add-pdf-password-and-security
'''*
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")
Digitally Sign PDFs
You can also digitally sign a PDF as follows:
C#:
/**
Digitally Sign PDF
anchor-digitally-sign-pdfs
**/
PdfDocument Pdf = PdfDocument.FromFile("testFile.pdf");
Pdf.QuickSignPdfWithDigitalSignatureFile("cert123.pfx", "123");
Pdf.SaveAs("signed.pdf");
VB:
'''
'''Digitally Sign PDF
'''anchor-digitally-sign-pdfs
'''*
Dim Pdf As PdfDocument = PdfDocument.FromFile("testFile.pdf")
Pdf.QuickSignPdfWithDigitalSignatureFile("cert123.pfx", "123")
Pdf.SaveAs("signed.pdf")
Advanced example for more control:
C#:
/**
Advanced Digitally Sign
anchor-digitally-sign-pdfs
**/
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(
VB:
'''
'''Advanced Digitally Sign
'''anchor-digitally-sign-pdfs
'''*
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(
12. Extract Text and Images from PDF
Extract text and images
Using IronPdf you can extract text and images from a PDF as follows:
C#:
/**
Extract Text and Images
anchor-extract-text-and-images-from-pdf
**/
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);
VB:
'''
'''Extract Text and Images
'''anchor-extract-text-and-images-from-pdf
'''*
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)
2.1 Rasterize PDF to Image
You can also convert PDF pages to images as follows:
C#:
/**
Rasterize PDF to Image
anchor-extract-text-and-images-from-pdf
**/
PdfDocument Pdf = PdfDocument.FromFile("testFile.pdf");
List<int> pageList = new List<int>() { 1,2};
Pdf.RasterizeToImageFiles("*.png", pageList);
VB:
'''
'''Rasterize PDF to Image
'''anchor-extract-text-and-images-from-pdf
'''*
Dim Pdf As PdfDocument = PdfDocument.FromFile("testFile.pdf")
Dim pageList As New List(Of Integer)() From {1, 2}
Pdf.RasterizeToImageFiles("*.png", pageList)
13. Add PDF Watermark
The following is an example of how to watermark PDF pages using the watermarkAllPages() method
C#:
/**
Add Watermark
anchor-add-pdf-watermark
**/
IronPdf.HtmlToPdf Renderer = new IronPdf.ChromePdfRenderer();
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");
VB:
'''
'''Add Watermark
'''anchor-add-pdf-watermark
'''*
Dim Renderer As IronPdf.HtmlToPdf = New IronPdf.ChromePdfRenderer()
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")
Watermark is restricted to basic position and a 100mm by 100mm as a maximum size. For more control you can use StampHTML method:
C#:
IronPdf.HtmlToPdf Renderer = new IronPdf.ChromePdfRenderer();
var pdf = Renderer.RenderHtmlAsPdf("<div>test text </div>");
var backgroundStamp = new IronPdf.Editing.HtmlStamp()
{
Html = "<h2 style='color:red'>copyright 2018 ironpdf.com",
Width = 100,
Height = 100,
Opacity = 50,
Rotation = -45,
ZIndex = IronPdf.Editing.HtmlStamp.StampLayer.BehindExistingPDFContent ,
Location = IronPdf.Editing.WaterMarkLocation.MiddleCenter
};
pdf.StampHTML(backgroundStamp);
pdf.SaveAs("stamped.pdf");
VB:
Dim Renderer As IronPdf.HtmlToPdf = New IronPdf.ChromePdfRenderer()
Dim pdf = Renderer.RenderHtmlAsPdf("<div>test text </div>")
Dim backgroundStamp = New IronPdf.Editing.HtmlStamp() With {
.Html = "<h2 style='color:red'>copyright 2018 ironpdf.com",
.Width = 100,
.Height = 100,
.Opacity = 50,
.Rotation = -45,
.ZIndex = IronPdf.Editing.HtmlStamp.StampLayer.BehindExistingPDFContent,
.Location = IronPdf.Editing.WaterMarkLocation.MiddleCenter
}
pdf.StampHTML(backgroundStamp)
pdf.SaveAs("stamped.pdf")
Top comments (0)