Generating PDFs in .NET Core API — Step-by-Step Tutorial
--
As a software developer, you may often need to generate PDF documents as part of your web application. It could be for generating invoices, receipts, or any other printable document. In this blog, we’ll explore how to generate PDFs in .NET Core API using a fun business problem alongside some examples so it can make sense. We’ll also use a popular third-party Nugget package to simplify the process.
Prerequisites
Before we begin, make sure you have the following installed on your system:
- .NET Core SDK
- Visual Studio Code or Visual Studio IDE
- SelectPdf Nugget package
Step 1: Create a new .NET Core API Project
Open Visual Studio or Visual Studio Code and create a new .NET Core API project. Let’s name it “PDFGeneratorAPI”.
Step 2: Install the SelectPdf Nugget Package
Right-click on the “PDFGeneratorAPI” project in the Solution Explorer and select “Manage NuGet Packages”. In the search box, type “SelectPdf” and select the “SelectPdf.HtmlToPdf” package. Click “Install” to install the package.
Step 3: Create a PDF Generator Service
Create a new folder named “Services” in the project root directory. Right-click on the folder and select “Add” -> “Class”. Name the class “PdfGeneratorService”.
In the class, create a method named “GeneratePdf” that takes a string parameter named “htmlContent” and returns a byte array. The method should use the SelectPdf package to convert the HTML content to PDF format and return the resulting byte array.
using SelectPdf;
public class PdfGeneratorService
{
public byte[] GeneratePdf(string htmlContent)
{
HtmlToPdf converter = new HtmlToPdf();
PdfDocument document = converter.ConvertHtmlString(htmlContent);
byte[] pdfBytes = document.Save();
document.Close();
return pdfBytes;
}
}
Step 4: Create a Controller for PDF Generation
Create a new folder named “Controllers” in the project root directory. Right-click on the folder and select “Add” -> “Controller”. Name the controller “PdfController”.