Test in production without watermarks.
Works wherever you need it to.
Get 30 days of fully functional product.
Have it up and running in minutes.
Full access to our support engineering team during your product trial
Swashbuckle is a C# .NET Core NuGet package that helps to automatically document RESTful Web APIs. In this blog, we are going to explore the Swashbuckle ASP.NET Core and IronPDF Installation Instructions NuGet packages, enabling the modern development of ASP.NET Core Web APIs. Together, they provide a host of functionalities that can be achieved with minimal code.
The API documentation pages are displayed using the Swagger UI tool, which uses a swagger.json
file generated from the Web API project. The generated JSON document follows the Open API standard. Swashbuckle is available as a NuGet package Swashbuckle.AspNetCore, which, when installed and configured, will automatically expose the Swagger JSON. The Swagger UI tool reads the Swagger JSON file, generated from XML comments written on the APIs. Additionally, an XML documentation file can be created by enabling it in the project settings file. XML comments are converted into an XML documentation file, from which the Swagger JSON is generated. Then the Swagger middleware reads the JSON and exposes Swagger JSON endpoints.
Let us start with a Web API project:
dotnet new webapi -n SwashbuckleDemo
cd SwashbuckleDemo
dotnet build
dotnet add package Swashbuckle.AspNetCore --version 6.5.0
dotnet build
dotnet new webapi -n SwashbuckleDemo
cd SwashbuckleDemo
dotnet build
dotnet add package Swashbuckle.AspNetCore --version 6.5.0
dotnet build
Here, we create a web API project named "SwashbuckleDemo" and then install the Swashbuckle package to the .NET Core Web API project using the Package Manager Console.
Configure Swagger services in the Startup.cs
file.
using System.Reflection;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Builder;
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
// Other service configurations...
// Register the Swagger generator
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
// Optionally, include XML comments for additional information
var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
c.IncludeXmlComments(xmlPath);
});
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
// Other app configurations...
// Enable middleware to serve generated Swagger as a JSON endpoint.
app.UseSwagger();
// Enable Swagger UI (HTML, JS, CSS, etc.), specifying the Swagger JSON endpoint.
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
});
}
}
using System.Reflection;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Builder;
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
// Other service configurations...
// Register the Swagger generator
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
// Optionally, include XML comments for additional information
var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
c.IncludeXmlComments(xmlPath);
});
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
// Other app configurations...
// Enable middleware to serve generated Swagger as a JSON endpoint.
app.UseSwagger();
// Enable Swagger UI (HTML, JS, CSS, etc.), specifying the Swagger JSON endpoint.
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
});
}
}
Imports System.Reflection
Imports Microsoft.Extensions.DependencyInjection
Imports Microsoft.AspNetCore.Builder
Public Class Startup
Public Sub ConfigureServices(ByVal services As IServiceCollection)
' Other service configurations...
' Register the Swagger generator
services.AddSwaggerGen(Sub(c)
c.SwaggerDoc("v1", New OpenApiInfo With {
.Title = "My API",
.Version = "v1"
})
' Optionally, include XML comments for additional information
Dim xmlFile = $"{System.Reflection.Assembly.GetExecutingAssembly().GetName().Name}.xml"
Dim xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile)
c.IncludeXmlComments(xmlPath)
End Sub)
End Sub
Public Sub Configure(ByVal app As IApplicationBuilder, ByVal env As IHostingEnvironment)
' Other app configurations...
' Enable middleware to serve generated Swagger as a JSON endpoint.
app.UseSwagger()
' Enable Swagger UI (HTML, JS, CSS, etc.), specifying the Swagger JSON endpoint.
app.UseSwaggerUI(Sub(c)
c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1")
End Sub)
End Sub
End Class
Add a controller for todo list APIs:
using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.AspNetCore.Builder;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;
// Example to define an entity class
public class Todo
{
public int Id { get; set; }
public string Name { get; set; }
public bool IsComplete { get; set; }
}
// Example to define a DbContext class
public class TodoDb : DbContext
{
public DbSet<Todo> Todos => Set<Todo>();
}
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.MapGet("/", () => "SwashbuckleDemo!");
app.MapGet("/todoitems", async (TodoDb db) =>
await db.Todos.ToListAsync());
app.MapGet("/todoitems/complete", async (TodoDb db) =>
await db.Todos.Where(t => t.IsComplete).ToListAsync());
app.MapGet("/todoitems/{id}", async (int id, TodoDb db) =>
await db.Todos.FindAsync(id) is Todo todo
? Results.Ok(todo)
: Results.NotFound());
app.MapPost("/todoitems", async (Todo todo, TodoDb db) =>
{
db.Todos.Add(todo);
await db.SaveChangesAsync();
return Results.Created($"/todoitems/{todo.Id}", todo);
});
app.MapPut("/todoitems/{id}", async (int id, Todo inputTodo, TodoDb db) =>
{
var todo = await db.Todos.FindAsync(id);
if (todo is null) return Results.NotFound();
todo.Name = inputTodo.Name;
todo.IsComplete = inputTodo.IsComplete;
await db.SaveChangesAsync();
return Results.NoContent();
});
app.MapDelete("/todoitems/{id}", async (int id, TodoDb db) =>
{
if (await db.Todos.FindAsync(id) is Todo todo)
{
db.Todos.Remove(todo);
await db.SaveChangesAsync();
return Results.Ok(todo);
}
return Results.NotFound();
});
app.Run();
using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.AspNetCore.Builder;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;
// Example to define an entity class
public class Todo
{
public int Id { get; set; }
public string Name { get; set; }
public bool IsComplete { get; set; }
}
// Example to define a DbContext class
public class TodoDb : DbContext
{
public DbSet<Todo> Todos => Set<Todo>();
}
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.MapGet("/", () => "SwashbuckleDemo!");
app.MapGet("/todoitems", async (TodoDb db) =>
await db.Todos.ToListAsync());
app.MapGet("/todoitems/complete", async (TodoDb db) =>
await db.Todos.Where(t => t.IsComplete).ToListAsync());
app.MapGet("/todoitems/{id}", async (int id, TodoDb db) =>
await db.Todos.FindAsync(id) is Todo todo
? Results.Ok(todo)
: Results.NotFound());
app.MapPost("/todoitems", async (Todo todo, TodoDb db) =>
{
db.Todos.Add(todo);
await db.SaveChangesAsync();
return Results.Created($"/todoitems/{todo.Id}", todo);
});
app.MapPut("/todoitems/{id}", async (int id, Todo inputTodo, TodoDb db) =>
{
var todo = await db.Todos.FindAsync(id);
if (todo is null) return Results.NotFound();
todo.Name = inputTodo.Name;
todo.IsComplete = inputTodo.IsComplete;
await db.SaveChangesAsync();
return Results.NoContent();
});
app.MapDelete("/todoitems/{id}", async (int id, TodoDb db) =>
{
if (await db.Todos.FindAsync(id) is Todo todo)
{
db.Todos.Remove(todo);
await db.SaveChangesAsync();
return Results.Ok(todo);
}
return Results.NotFound();
});
app.Run();
Imports Microsoft.AspNetCore.Http.HttpResults
Imports Microsoft.AspNetCore.Builder
Imports Microsoft.EntityFrameworkCore
Imports Microsoft.AspNetCore.Mvc
Imports System.Threading.Tasks
' Example to define an entity class
Public Class Todo
Public Property Id() As Integer
Public Property Name() As String
Public Property IsComplete() As Boolean
End Class
' Example to define a DbContext class
Public Class TodoDb
Inherits DbContext
Public ReadOnly Property Todos() As DbSet(Of Todo)
Get
Return [Set](Of Todo)()
End Get
End Property
End Class
Private builder = WebApplication.CreateBuilder(args)
Private app = builder.Build()
app.MapGet("/", Function() "SwashbuckleDemo!")
app.MapGet("/todoitems", Async Function(db As TodoDb) Await db.Todos.ToListAsync())
app.MapGet("/todoitems/complete", Async Function(db As TodoDb) Await db.Todos.Where(Function(t) t.IsComplete).ToListAsync())
Dim tempVar As Boolean = TypeOf db.Todos.FindAsync(id) Is Todo
Dim todo As Todo = If(tempVar, CType(db.Todos.FindAsync(id), Todo), Nothing)
app.MapGet("/todoitems/{id}", Async Function(id As Integer, db As TodoDb)If(Await tempVar, Results.Ok(todo), Results.NotFound()))
app.MapPost("/todoitems", Async Function(todo As Todo, db As TodoDb)
db.Todos.Add(todo)
Await db.SaveChangesAsync()
Return Results.Created($"/todoitems/{todo.Id}", todo)
End Function)
app.MapPut("/todoitems/{id}", Async Function(id As Integer, inputTodo As Todo, db As TodoDb)
Dim todo = Await db.Todos.FindAsync(id)
If todo Is Nothing Then
Return Results.NotFound()
End If
todo.Name = inputTodo.Name
todo.IsComplete = inputTodo.IsComplete
Await db.SaveChangesAsync()
Return Results.NoContent()
End Function)
app.MapDelete("/todoitems/{id}", Async Function(id As Integer, db As TodoDb)
Dim tempVar2 As Boolean = TypeOf db.Todos.FindAsync(id) Is Todo
Dim todo As Todo = If(tempVar2, CType(db.Todos.FindAsync(id), Todo), Nothing)
If Await tempVar2 Then
db.Todos.Remove(todo)
Await db.SaveChangesAsync()
Return Results.Ok(todo)
End If
Return Results.NotFound()
End Function)
app.Run()
A controller can also be added like below:
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System.Collections.Generic;
using System;
using System.Linq;
namespace RestFullMinimalApi.Controllers
{
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
private static readonly string[] Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
private readonly ILogger<WeatherForecastController> _logger;
public WeatherForecastController(ILogger<WeatherForecastController> logger)
{
_logger = logger;
}
/// <summary>
/// Retrieves WeatherForecast
/// </summary>
/// <remarks>Awesomeness!</remarks>
/// <response code="200">Retrieved</response>
/// <response code="404">Not found</response>
/// <response code="500">Oops! Can't lookup your request right now</response>
[HttpGet(Name = "GetWeatherForecast")]
public IEnumerable<WeatherForecast> Get()
{
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),
TemperatureC = Random.Shared.Next(-20, 55),
Summary = Summaries[Random.Shared.Next(Summaries.Length)]
})
.ToArray();
}
}
public class WeatherForecast
{
public DateTime Date { get; set; }
public int TemperatureC { get; set; }
public string Summary { get; set; }
}
}
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System.Collections.Generic;
using System;
using System.Linq;
namespace RestFullMinimalApi.Controllers
{
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
private static readonly string[] Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
private readonly ILogger<WeatherForecastController> _logger;
public WeatherForecastController(ILogger<WeatherForecastController> logger)
{
_logger = logger;
}
/// <summary>
/// Retrieves WeatherForecast
/// </summary>
/// <remarks>Awesomeness!</remarks>
/// <response code="200">Retrieved</response>
/// <response code="404">Not found</response>
/// <response code="500">Oops! Can't lookup your request right now</response>
[HttpGet(Name = "GetWeatherForecast")]
public IEnumerable<WeatherForecast> Get()
{
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),
TemperatureC = Random.Shared.Next(-20, 55),
Summary = Summaries[Random.Shared.Next(Summaries.Length)]
})
.ToArray();
}
}
public class WeatherForecast
{
public DateTime Date { get; set; }
public int TemperatureC { get; set; }
public string Summary { get; set; }
}
}
Imports Microsoft.AspNetCore.Mvc
Imports Microsoft.Extensions.Logging
Imports System.Collections.Generic
Imports System
Imports System.Linq
Namespace RestFullMinimalApi.Controllers
<ApiController>
<Route("[controller]")>
Public Class WeatherForecastController
Inherits ControllerBase
Private Shared ReadOnly Summaries() As String = { "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" }
Private ReadOnly _logger As ILogger(Of WeatherForecastController)
Public Sub New(ByVal logger As ILogger(Of WeatherForecastController))
_logger = logger
End Sub
''' <summary>
''' Retrieves WeatherForecast
''' </summary>
''' <remarks>Awesomeness!</remarks>
''' <response code="200">Retrieved</response>
''' <response code="404">Not found</response>
''' <response code="500">Oops! Can't lookup your request right now</response>
<HttpGet(Name := "GetWeatherForecast")>
Public Function [Get]() As IEnumerable(Of WeatherForecast)
Return Enumerable.Range(1, 5).Select(Function(index) New WeatherForecast With {
.Date = DateTime.Now.AddDays(index),
.TemperatureC = Random.Shared.Next(-20, 55),
.Summary = Summaries(Random.Shared.Next(Summaries.Length))
}).ToArray()
End Function
End Class
Public Class WeatherForecast
Public Property [Date]() As DateTime
Public Property TemperatureC() As Integer
Public Property Summary() As String
End Class
End Namespace
The above code is available on GitHub - Swashbuckle Demo.
Swagger UI is available at "/swagger/index.html" from the base URL of the Web API application. It lists all the REST APIs from the code. The Swagger generator reads the JSON file and populates the UI.
Swashbuckle.AspNetCore automatically generates the Swagger JSON file, which contains information about the API's structure, including details such as endpoints, request and response types, and more. This JSON file can be used by other tools and services that support the Swagger/OpenAPI standard.
The Swagger JSON file is available at "/swagger/v1/swagger.json" from the base URL of the web API application.
Developers can use XML comments and attributes within their ASP.NET Core controllers to provide additional information for Swagger documentation. This includes descriptions, examples, and other metadata that enhances the generated Swagger documentation.
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
private static readonly string[] Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
private readonly ILogger<WeatherForecastController> _logger;
public WeatherForecastController(ILogger<WeatherForecastController> logger)
{
_logger = logger;
}
/// <summary>
/// Retrieves WeatherForecast
/// </summary>
/// <remarks>Awesomeness!</remarks>
/// <response code="200">Retrieved</response>
/// <response code="404">Not found</response>
/// <response code="500">Oops! Can't lookup your request right now</response>
[HttpGet(Name = "GetWeatherForecast")]
public IEnumerable<WeatherForecast> Get()
{
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),
TemperatureC = Random.Shared.Next(-20, 55),
Summary = Summaries[Random.Shared.Next(Summaries.Length)]
})
.ToArray();
}
}
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
private static readonly string[] Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
private readonly ILogger<WeatherForecastController> _logger;
public WeatherForecastController(ILogger<WeatherForecastController> logger)
{
_logger = logger;
}
/// <summary>
/// Retrieves WeatherForecast
/// </summary>
/// <remarks>Awesomeness!</remarks>
/// <response code="200">Retrieved</response>
/// <response code="404">Not found</response>
/// <response code="500">Oops! Can't lookup your request right now</response>
[HttpGet(Name = "GetWeatherForecast")]
public IEnumerable<WeatherForecast> Get()
{
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),
TemperatureC = Random.Shared.Next(-20, 55),
Summary = Summaries[Random.Shared.Next(Summaries.Length)]
})
.ToArray();
}
}
<ApiController>
<Route("[controller]")>
Public Class WeatherForecastController
Inherits ControllerBase
Private Shared ReadOnly Summaries() As String = { "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" }
Private ReadOnly _logger As ILogger(Of WeatherForecastController)
Public Sub New(ByVal logger As ILogger(Of WeatherForecastController))
_logger = logger
End Sub
''' <summary>
''' Retrieves WeatherForecast
''' </summary>
''' <remarks>Awesomeness!</remarks>
''' <response code="200">Retrieved</response>
''' <response code="404">Not found</response>
''' <response code="500">Oops! Can't lookup your request right now</response>
<HttpGet(Name := "GetWeatherForecast")>
Public Function [Get]() As IEnumerable(Of WeatherForecast)
Return Enumerable.Range(1, 5).Select(Function(index) New WeatherForecast With {
.Date = DateTime.Now.AddDays(index),
.TemperatureC = Random.Shared.Next(-20, 55),
.Summary = Summaries(Random.Shared.Next(Summaries.Length))
}).ToArray()
End Function
End Class
Swashbuckle.AspNetCore provides various configuration options to customize how Swagger documentation is generated. Developers can control which APIs are documented, configure naming conventions, and adjust other settings.
Here are some of the key configuration options provided by Swashbuckle.AspNetCore:
c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
c.SwaggerDoc("v1", New OpenApiInfo With {
.Title = "My API",
.Version = "v1"
})
This line specifies the Swagger document version and includes metadata such as the title and version of your API.
c.IncludeXmlComments(xmlPath);
c.IncludeXmlComments(xmlPath);
c.IncludeXmlComments(xmlPath)
This option allows you to include XML comments from your code to provide additional information in the Swagger documentation. The xmlPath
variable should point to the location of your XML comments file.
c.DescribeAllParametersInCamelCase();
c.DescribeAllParametersInCamelCase();
c.DescribeAllParametersInCamelCase()
This option configures the Swagger generator to use camelCase for parameter names.
c.OperationFilter<CustomOperationFilter>();
c.OperationFilter<CustomOperationFilter>();
c.OperationFilter(Of CustomOperationFilter)()
You can register custom operation filters to modify the Swagger documentation for specific operations. CustomOperationFilter
is a class that implements IOperationFilter
.
c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1")
This line configures the Swagger UI to display documentation. The first parameter is the URL of the Swagger JSON file, and the second parameter is a user-friendly name for the API version.
c.RoutePrefix = "swagger";
c.RoutePrefix = "swagger";
c.RoutePrefix = "swagger"
You can set the route prefix for the Swagger UI. In this example, the Swagger UI will be available at /swagger.
c.DocExpansion(DocExpansion.None);
c.DocExpansion(DocExpansion.None);
c.DocExpansion(DocExpansion.None)
This option controls how the Swagger UI displays the API documentation. DocExpansion.None
collapses all the operations by default.
c.SerializeAsV2 = true;
c.SerializeAsV2 = true;
c.SerializeAsV2 = True
This option specifies whether to serialize the Swagger document in version 2.0 format (true
) or 3.0 format (false
). Set it to true
if you want to use Swagger 2.0.
c.DisplayOperationId();
c.DisplayOperationId();
c.DisplayOperationId()
This option displays the operation ID in the Swagger UI, which can be useful for debugging and understanding the structure of your API.
c.OAuthClientId("swagger-ui");
c.OAuthClientId("swagger-ui");
c.OAuthClientId("swagger-ui")
If your API uses OAuth authentication, you can configure the OAuth client ID for Swagger UI.
These are just a few examples of the configuration options available. The Swashbuckle.AspNetCore library is highly customizable, and you can tailor the Swagger documentation to meet your specific needs by combining various options and filters. Always refer to the official documentation or IntelliSense in your development environment for the most up-to-date and comprehensive information on available options.
IronPDF Product Overview is the C# PDF Library from Iron Software Website that helps to read and generate PDF documents. It can easily convert formatted documents with style information to PDF. IronPDF can effortlessly generate PDFs from HTML content. It can download the HTML content from a URL and then generate PDFs.
IronPDF is a great tool for converting web pages, URLs, and HTML into PDFs that perfectly replicate the source. It is ideal for generating PDFs of online content such as reports and invoices, and effortlessly creates PDF versions of any webpage.
using IronPdf;
class Program
{
static void Main(string[] args)
{
var renderer = new ChromePdfRenderer();
// 1. Convert HTML String to PDF
var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");
// 2. Convert HTML File to PDF
var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");
// 3. Convert URL to PDF
var url = "http://ironpdf.com"; // Specify the URL
var pdfFromUrl = renderer.RenderUrlAsPdf(url);
pdfFromUrl.SaveAs("URLToPDF.pdf");
}
}
using IronPdf;
class Program
{
static void Main(string[] args)
{
var renderer = new ChromePdfRenderer();
// 1. Convert HTML String to PDF
var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");
// 2. Convert HTML File to PDF
var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");
// 3. Convert URL to PDF
var url = "http://ironpdf.com"; // Specify the URL
var pdfFromUrl = renderer.RenderUrlAsPdf(url);
pdfFromUrl.SaveAs("URLToPDF.pdf");
}
}
Imports IronPdf
Friend Class Program
Shared Sub Main(ByVal args() As String)
Dim renderer = New ChromePdfRenderer()
' 1. Convert HTML String to PDF
Dim htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>"
Dim pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent)
pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf")
' 2. Convert HTML File to PDF
Dim htmlFilePath = "path_to_your_html_file.html" ' Specify the path to your HTML file
Dim pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath)
pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf")
' 3. Convert URL to PDF
Dim url = "http://ironpdf.com" ' Specify the URL
Dim pdfFromUrl = renderer.RenderUrlAsPdf(url)
pdfFromUrl.SaveAs("URLToPDF.pdf")
End Sub
End Class
Install IronPDF via NuGet using the NuGet Package Manager Details or the Visual Studio Installation Guide package manager console.
In the Package Manager Console, input the command:
Install-Package IronPdf
Using Visual Studio
Now, let's modify our application to add functionality to download website content as a PDF file.
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using IronPdf;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace RestFullMinimalApi.Controllers
{
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
private static readonly string[] Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
private readonly ILogger<WeatherForecastController> _logger;
public WeatherForecastController(ILogger<WeatherForecastController> logger)
{
_logger = logger;
}
/// <summary>
/// Retrieves WeatherForecast
/// </summary>
/// <remarks>Awesomeness!</remarks>
/// <response code="200">Retrieved</response>
/// <response code="404">Not found</response>
/// <response code="500">Oops! Can't lookup your request right now</response>
[HttpGet(Name = "GetWeatherForecast")]
public IEnumerable<WeatherForecast> Get()
{
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),
TemperatureC = Random.Shared.Next(-20, 55),
Summary = Summaries[Random.Shared.Next(Summaries.Length)]
})
.ToArray();
}
/// <summary>
/// Retrieves WeatherForecast as Pdf
/// </summary>
/// <remarks>Awesomeness!</remarks>
/// <response code="200">Retrieved</response>
/// <response code="404">Not found</response>
/// <response code="500">Oops! Can't lookup your request right now</response>
[HttpGet("download", Name = "DownloadWeatherForecast")]
public IActionResult GetWeatherPdf()
{
var results = Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),
TemperatureC = Random.Shared.Next(-20, 55),
Summary = Summaries[Random.Shared.Next(Summaries.Length)]
}).ToArray();
var html = GetHtml(results);
var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderHtmlAsPdf(html);
var fileName = "WeatherReport.pdf";
pdf.SaveAs(fileName);
var stream = new FileStream(fileName, FileMode.Open);
// Return the PDF file for download
return new FileStreamResult(stream, "application/octet-stream") { FileDownloadName = fileName };
}
private static string GetHtml(WeatherForecast[] weatherForecasts)
{
string header = @"
<html>
<head><title>WeatherForecast</title></head>
<body>
<h1>WeatherForecast</h1>
";
var footer = @"
</body>
</html>";
var htmlContent = header;
foreach (var weather in weatherForecasts)
{
htmlContent += $@"
<h2>{weather.Date}</h2>
<p>Summary: {weather.Summary}</p>
<p>Temperature in Celsius: {weather.TemperatureC}</p>
<p>Temperature in Fahrenheit: {weather.TemperatureF}</p>
";
}
htmlContent += footer;
return htmlContent;
}
}
public class WeatherForecast
{
public DateTime Date { get; set; }
public int TemperatureC { get; set; }
public string Summary { get; set; }
public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
}
}
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using IronPdf;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace RestFullMinimalApi.Controllers
{
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
private static readonly string[] Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
private readonly ILogger<WeatherForecastController> _logger;
public WeatherForecastController(ILogger<WeatherForecastController> logger)
{
_logger = logger;
}
/// <summary>
/// Retrieves WeatherForecast
/// </summary>
/// <remarks>Awesomeness!</remarks>
/// <response code="200">Retrieved</response>
/// <response code="404">Not found</response>
/// <response code="500">Oops! Can't lookup your request right now</response>
[HttpGet(Name = "GetWeatherForecast")]
public IEnumerable<WeatherForecast> Get()
{
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),
TemperatureC = Random.Shared.Next(-20, 55),
Summary = Summaries[Random.Shared.Next(Summaries.Length)]
})
.ToArray();
}
/// <summary>
/// Retrieves WeatherForecast as Pdf
/// </summary>
/// <remarks>Awesomeness!</remarks>
/// <response code="200">Retrieved</response>
/// <response code="404">Not found</response>
/// <response code="500">Oops! Can't lookup your request right now</response>
[HttpGet("download", Name = "DownloadWeatherForecast")]
public IActionResult GetWeatherPdf()
{
var results = Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),
TemperatureC = Random.Shared.Next(-20, 55),
Summary = Summaries[Random.Shared.Next(Summaries.Length)]
}).ToArray();
var html = GetHtml(results);
var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderHtmlAsPdf(html);
var fileName = "WeatherReport.pdf";
pdf.SaveAs(fileName);
var stream = new FileStream(fileName, FileMode.Open);
// Return the PDF file for download
return new FileStreamResult(stream, "application/octet-stream") { FileDownloadName = fileName };
}
private static string GetHtml(WeatherForecast[] weatherForecasts)
{
string header = @"
<html>
<head><title>WeatherForecast</title></head>
<body>
<h1>WeatherForecast</h1>
";
var footer = @"
</body>
</html>";
var htmlContent = header;
foreach (var weather in weatherForecasts)
{
htmlContent += $@"
<h2>{weather.Date}</h2>
<p>Summary: {weather.Summary}</p>
<p>Temperature in Celsius: {weather.TemperatureC}</p>
<p>Temperature in Fahrenheit: {weather.TemperatureF}</p>
";
}
htmlContent += footer;
return htmlContent;
}
}
public class WeatherForecast
{
public DateTime Date { get; set; }
public int TemperatureC { get; set; }
public string Summary { get; set; }
public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
}
}
Imports Microsoft.AspNetCore.Mvc
Imports Microsoft.Extensions.Logging
Imports IronPdf
Imports System
Imports System.Collections.Generic
Imports System.IO
Imports System.Linq
Namespace RestFullMinimalApi.Controllers
<ApiController>
<Route("[controller]")>
Public Class WeatherForecastController
Inherits ControllerBase
Private Shared ReadOnly Summaries() As String = { "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" }
Private ReadOnly _logger As ILogger(Of WeatherForecastController)
Public Sub New(ByVal logger As ILogger(Of WeatherForecastController))
_logger = logger
End Sub
''' <summary>
''' Retrieves WeatherForecast
''' </summary>
''' <remarks>Awesomeness!</remarks>
''' <response code="200">Retrieved</response>
''' <response code="404">Not found</response>
''' <response code="500">Oops! Can't lookup your request right now</response>
<HttpGet(Name := "GetWeatherForecast")>
Public Function [Get]() As IEnumerable(Of WeatherForecast)
Return Enumerable.Range(1, 5).Select(Function(index) New WeatherForecast With {
.Date = DateTime.Now.AddDays(index),
.TemperatureC = Random.Shared.Next(-20, 55),
.Summary = Summaries(Random.Shared.Next(Summaries.Length))
}).ToArray()
End Function
''' <summary>
''' Retrieves WeatherForecast as Pdf
''' </summary>
''' <remarks>Awesomeness!</remarks>
''' <response code="200">Retrieved</response>
''' <response code="404">Not found</response>
''' <response code="500">Oops! Can't lookup your request right now</response>
<HttpGet("download", Name := "DownloadWeatherForecast")>
Public Function GetWeatherPdf() As IActionResult
Dim results = Enumerable.Range(1, 5).Select(Function(index) New WeatherForecast With {
.Date = DateTime.Now.AddDays(index),
.TemperatureC = Random.Shared.Next(-20, 55),
.Summary = Summaries(Random.Shared.Next(Summaries.Length))
}).ToArray()
Dim html = GetHtml(results)
Dim renderer = New ChromePdfRenderer()
Dim pdf = renderer.RenderHtmlAsPdf(html)
Dim fileName = "WeatherReport.pdf"
pdf.SaveAs(fileName)
Dim stream = New FileStream(fileName, FileMode.Open)
' Return the PDF file for download
Return New FileStreamResult(stream, "application/octet-stream") With {.FileDownloadName = fileName}
End Function
Private Shared Function GetHtml(ByVal weatherForecasts() As WeatherForecast) As String
Dim header As String = "
<html>
<head><title>WeatherForecast</title></head>
<body>
<h1>WeatherForecast</h1>
"
Dim footer = "
</body>
</html>"
Dim htmlContent = header
For Each weather In weatherForecasts
htmlContent &= $"
<h2>{weather.Date}</h2>
<p>Summary: {weather.Summary}</p>
<p>Temperature in Celsius: {weather.TemperatureC}</p>
<p>Temperature in Fahrenheit: {weather.TemperatureF}</p>
"
Next weather
htmlContent &= footer
Return htmlContent
End Function
End Class
Public Class WeatherForecast
Public Property [Date]() As DateTime
Public Property TemperatureC() As Integer
Public Property Summary() As String
Public ReadOnly Property TemperatureF() As Integer
Get
Return 32 + CInt(Math.Truncate(TemperatureC / 0.5556))
End Get
End Property
End Class
End Namespace
Here, we use the weather data to generate an HTML string, which is then used to create a PDF document.
And the PDF report looks like this:
The entire code can be found on GitHub - Swashbuckle Demo Source Code.
The document has a small watermark for trial licenses, removable with a valid license.
For the above code to work, a license key is required. Place this key in the appsettings.json
file.
{
"IronPdf": {
"LicenseKey": "your license key"
}
}
A trial license is available for developers upon registering with IronPDF Trial Registration. No credit card is needed for a trial license. Register with your email address to obtain a free trial.
Understanding Swashbuckle and IronPDF allows you to effectively integrate API documentation and PDF generation capabilities into your ASP.NET Core applications. IronPDF also offers comprehensive documentation for Getting Started, along with various Code Examples for PDF Generation.
Additionally, you can explore related software products from Iron Software that will help you enhance your coding skills and meet modern application requirements.
Swashbuckle is a C# .NET Core NuGet package that helps automatically document RESTful Web APIs. It uses Swagger UI to display the API documentation, which is generated from XML comments in the code.
You can install Swashbuckle in a .NET Core project using the command: `dotnet add package Swashbuckle.AspNetCore --version 6.5.0` in the project directory.
The Swagger UI tool provides a visual interface to explore and test RESTful Web APIs. It reads the Swagger JSON file generated by Swashbuckle and displays it in a user-friendly format.
XML comments can be included in Swagger documentation by enabling XML documentation in the project settings and configuring Swashbuckle to read these comments using the `IncludeXmlComments` method.
IronPDF is a C# library that helps to read and generate PDF documents. It can convert HTML content, web pages, and URLs into PDFs, ideal for generating reports and invoices.
IronPDF can be installed via NuGet using the command: `Install-Package IronPdf` in the Package Manager Console.
Swashbuckle features include automatic generation of Swagger JSON, integration with Swagger UI, support for XML comments, and various configuration options to customize API documentation.
Swashbuckle offers configuration options such as setting document version, including XML comments, parameter naming conventions, and customizing UI elements like route prefixes and document expansion.
Swashbuckle benefits developers by simplifying the process of documenting APIs with minimal code effort, ensuring compliance with OpenAPI standards, and providing a visual interface for testing APIs.
To use IronPDF with a valid license, include the license key in the `appsettings.json` file under the `IronPdf` section as follows: `"IronPdf": { "LicenseKey": "your license key" }`.