Creating a downloadable PDF file using Blazor C#

2 min read 05-10-2024
Creating a downloadable PDF file using Blazor C#


Generate Downloadable PDF Files with Blazor C#

Problem: You need to create a downloadable PDF document from your Blazor C# application. Perhaps you want to generate invoices, reports, or other documents for users to save.

Solution: Blazor doesn't directly support creating PDF files, but there are several libraries that can help you achieve this. This article explores using iTextSharp, a popular and powerful library for PDF manipulation in C#.

Setting up iTextSharp

  1. Install the NuGet Package: Open your project's NuGet Package Manager and search for "itextsharp". Install the latest version.

  2. Add References: Ensure that you include the required references for iTextSharp in your Blazor component or page.

  3. Create a PDF Generator Service: Let's create a service to encapsulate the logic for PDF generation:

using iTextSharp.text;
using iTextSharp.text.pdf;

public class PdfGeneratorService
{
    public async Task<byte[]> GeneratePdf(string content)
    {
        // Create a new PDF document
        using var document = new Document();
        using var stream = new MemoryStream();
        using var writer = PdfWriter.GetInstance(document, stream);

        // Open the document
        document.Open();

        // Add content to the document
        Paragraph paragraph = new Paragraph(content);
        document.Add(paragraph);

        // Close the document
        document.Close();

        // Return the generated PDF as a byte array
        return stream.ToArray();
    }
}

This example demonstrates a basic PDF generation with text content. You can further customize the PDF by adding:

  • Headers and Footers: Using HeaderFooter class.
  • Images: Using Image class.
  • Tables: Using PdfPTable class.
  • Styling: Using Font and Paragraph properties.

Downloading the PDF

Now, let's create a Blazor component to trigger the download:

@page "/pdf-generator"
@inject PdfGeneratorService pdfGeneratorService

<h3>Generate PDF</h3>

<button class="btn btn-primary" @onclick="GeneratePdf">Download PDF</button>

@code {
    private async Task GeneratePdf()
    {
        // Generate the PDF content as a byte array
        byte[] pdfBytes = await pdfGeneratorService.GeneratePdf("This is some sample text for the PDF.");

        // Download the PDF using Blazor's DownloadFile method
        await JSRuntime.InvokeVoidAsync("downloadFile", "invoice.pdf", pdfBytes);
    }
}

This component defines a button that, when clicked, triggers the GeneratePdf method. This method calls the GeneratePdf service to create the PDF and then utilizes Blazor's JavaScript interop (JSRuntime) to download the generated file using the browser's built-in functionality.

Important Points

  • Security: Carefully handle user input and sanitize data before adding it to the PDF to prevent potential security issues.
  • Alternative Libraries: Explore other libraries like PdfSharp, Aspose.Pdf or ClosedXML for different features and functionalities.
  • Error Handling: Implement robust error handling for potential issues during PDF generation and download.

By following these steps and understanding the concepts, you can effectively create and download PDF documents from your Blazor C# applications.