Introduction
Generating PDF files in an ASP.NET Core Web API is a common requirement, and there are several libraries available to help with this task. In this example, I'll show you how to generate PDF files using the popular library called DinkToPdf, which is a .NET wrapper for the C library DinkToPdf. We'll also follow best practices for structuring your ASP.NET Core Web API project.
Step 1. Create a New ASP.NET Core Web API Project
You can create a new ASP.NET Core Web API project using Visual Studio or the .NET CLI.
dotnet new webapi -n PdfGeneratorApi
cd PdfGeneratorApi
Step 2. Install DinkToPdf
You can add the DinkToPdf library to your project using NuGet Package Manager or by editing the .csproj file directly. Here's how to add it via the Package Manager Console.
Install-Package DinkToPdf
Step 3. Configure DinkToPdf
In your Startup.cs file, add the following code to configure DinkToPdf.
using DinkToPdf;
Author: Sardar Mudassar Ali Khan
// Inside ConfigureServices method
services.AddSingleton(typeof(IConverter), new SynchronizedConverter(new PdfTools()));
// Make sure you have the DinkToPdf binaries copied to your project's output directory.
Step 4. Create a PDF Service
Now, let's create a service that will handle PDF generation. Create a new folder called Services in your project, and add a class named PdfService.cs.
using DinkToPdf;
using System.IO;
Author: Sardar Mudassar Ali Khan
public class PdfService
{
private readonly IConverter _converter;
public PdfService(IConverter converter)
{
_converter = converter;
}
public byte[] GeneratePdf(string htmlContent)
{
var globalSettings = new GlobalSettings
{
PaperSize = PaperKind.A4,
Orientation = Orientation.Portrait,
};
var objectSettings = new ObjectSettings
{
PagesCount = true,
HtmlContent = htmlContent,
};
var pdf = new HtmlToPdfDocument()
{
GlobalSettings = globalSettings,
Objects = { objectSettings },
};
return _converter.Convert(pdf);
}
}
Step 5. Create a Controller for PDF Generation
Now, let's create a controller that will expose an API endpoint for generating PDF files. Create a controller named PdfController.cs.
using Microsoft.AspNetCore.Mvc;
using System.Text;
Author: Sardar Mudassar Ali Khan
[Route("api/[controller]")]
[ApiController]
public class PdfController : ControllerBase
{
private readonly PdfService _pdfService;
public PdfController(PdfService pdfService)
{
_pdfService = pdfService;
}
[HttpPost]
[Route("generate")]
public IActionResult GeneratePdf([FromBody] PdfRequest request)
{
if (request == null || string.IsNullOrWhiteSpace(request.HtmlContent))
{
return BadRequest("Invalid request.");
}
var pdfBytes = _pdfService.GeneratePdf(request.HtmlContent);
return File(pdfBytes, "application/pdf", "generated.pdf");
}
}
public class PdfRequest
{
public string HtmlContent { get; set; }
}
Step 6. Configure CORS (if needed)
If your API needs to be accessed from a different domain, consider configuring CORS in your Startup.cs.
// Inside ConfigureServices method
Author: Sardar Mudassar Ali Khan
services.AddCors();
// Inside Configure method, before app.UseAuthorization()
app.UseCors(builder =>
{
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
});
Step 7. Test Your PDF Generation API
- You can now test your PDF generation API by sending a POST request to /api/pdf/generate with a JSON payload containing the HTML content you want to convert to a PDF.
- Remember to install a tool like Postman or use cURL to make HTTP requests to your API.
- That's it! You now have a working ASP.NET Core Web API for generating PDF files using the DinkToPdf library and following best practices.
Conclusion
In this example, we've created an ASP.NET Core Web API for generating PDF files using the DinkToPdf library while adhering to best practices. Here's a recap of the key steps.
- Create a New ASP.NET Core Web API Project: Start by creating a new ASP.NET Core Web API project.
- Install DinkToPdf: Add the DinkToPdf library to your project using NuGet Package Manager.
- Configure DinkToPdf: In the Startup.cs file, configure DinkToPdf by registering it as a service in the ConfigureServices method.
- Create a PDF Service: Create a PdfService class to handle PDF generation. This service uses DinkToPdf to convert HTML content to PDF.
- Create a Controller for PDF Generation: Create a controller named PdfController to expose an API endpoint for generating PDF files. This controller takes HTML content as input and returns the generated PDF.
- Configure CORS (if needed): If your API needs to be accessed from a different domain, configure CORS in the Startup.cs file.
- Test Your PDF Generation API: Test your API by sending a POST request to /api/pdf/generate with a JSON payload containing the HTML content to be converted to a PDF.
By following these steps, you've successfully set up a PDF generation API in your ASP.NET Core Web API project, allowing you to generate PDF files from HTML content efficiently and according to best practices. You can further enhance this API by adding error handling, authentication, and authorization as needed for your specific application.