Codementor Events

PDF Generation with Blazor and PdfSharp

Published Sep 27, 2024

PDF Generation with Blazor, PDFsharp, and MigraDoc: A Comprehensive Guide

This article explores how Blazor, combined with PDFsharp and MigraDoc, can be leveraged to create dynamic PDF documents directly within a web application. The project BlazorSharpProject demonstrates this integration using both Blazor WebAssembly and Blazor Server.


Introduction to Blazor, PDFsharp, and MigraDoc

Blazor is a modern framework by Microsoft that allows developers to build interactive web applications using C# and .NET. It supports two hosting models:

  1. Blazor Server: Executes server-side, with the UI updated in real-time via SignalR.
  2. Blazor WebAssembly: Runs client-side, using WebAssembly to execute .NET code in the browser.

PDFsharp is a .NET library used to create PDF documents from scratch. It allows for low-level manipulation of PDFs, including drawing text, graphics, and images. MigraDoc, on the other hand, is a higher-level library built on top of PDFsharp that provides a simple API for generating well-formatted documents with sections, paragraphs, tables, headers, and footers. The combination of PDFsharp and MigraDoc offers a powerful solution for creating PDFs with a rich structure and design.


Why Choose Blazor for PDF Generation?

Blazor is a compelling choice for generating PDFs due to the following reasons:

  1. Unified C# Development: You can write both frontend and backend logic in C#, leveraging the existing .NET ecosystem.
  2. Real-Time PDF Export: With Blazor’s interactive UI, users can easily export their data into well-structured PDFs, such as reports, invoices, or summaries.
  3. Flexibility with Hosting Models: Blazor allows you to choose between a server-side approach with Blazor Server for complex processing or a client-side model using Blazor WebAssembly, offering flexibility based on your application's requirements.

Overview of the BlazorSharpProject

The BlazorSharpProject demonstrates how to integrate PDF generation into both Blazor WebAssembly and Blazor Server. This project showcases the capabilities of PDFsharp and MigraDoc to create customized PDFs, such as reports or dynamic forms, directly from a Blazor application.

Key Features of the Project

  • PDF Generation on the Fly: Users can generate PDFs dynamically based on interactions with the UI, such as form inputs or table data.
  • Customizable Layout: Use MigraDoc to create structured documents with titles, headers, footers, images, and tables.
  • Cross-Platform: The project supports both Blazor Server and Blazor WebAssembly models:
    • Blazor Server handles processing server-side for scalability and performance.
    • Blazor WebAssembly processes PDF generation in the client browser, reducing server load.
  • Modular Architecture: The project is built with a focus on reusability and scalability. The PDF generation logic is encapsulated in services and can easily be integrated into any part of the Blazor application.

Integrating PDFsharp and MigraDoc into Blazor

1. Setting Up the Libraries

To integrate PDFsharp and MigraDoc into your Blazor project, you first need to install the required NuGet packages:

dotnet add package PdfSharp
dotnet add package PdfSharp-MigraDoc

These packages provide all the tools needed to generate PDFs, including text, images, tables, and more.

2. Creating the PDF Generation Service

PDF generation logic is best encapsulated in a service that handles the document creation. Below is a sample service that demonstrates how to create a basic PDF document:

using PdfSharp.Pdf;
using PdfSharp.Drawing;
using MigraDoc.DocumentObjectModel;
using MigraDoc.Rendering;

public class PdfService
{
    public byte[] GeneratePdf(string title, string content)
    {
        // Create a new PDF document
        PdfDocument document = new PdfDocument();
        PdfPage page = document.AddPage();
        XGraphics gfx = XGraphics.FromPdfPage(page);

        // Add content with PDFsharp
        XFont font = new XFont("Verdana", 20, XFontStyle.Bold);
        gfx.DrawString(title, font, XBrushes.Black, new XRect(0, 0, page.Width, page.Height), XStringFormats.TopCenter);

        // Add more detailed content using MigraDoc
        Document doc = new Document();
        Section section = doc.AddSection();
        section.AddParagraph(content);

        // Render MigraDoc content
        PdfDocumentRenderer renderer = new PdfDocumentRenderer(true);
        renderer.Document = doc;
        renderer.RenderDocument();
        renderer.PdfDocument.Save("output.pdf");

        // Save PDF to memory stream
        using (var stream = new MemoryStream())
        {
            document.Save(stream, false);
            return stream.ToArray();
        }
    }
}

This service generates a PDF document that includes both basic content using PDFsharp and more detailed layout content using MigraDoc.

3. Integrating the Service with Blazor UI

Now that the service is set up, you can integrate it into your Blazor components. Below is an example of a Blazor component that triggers PDF generation when a button is clicked:

@inject PdfService PdfService

<button @onclick="GeneratePdf">Generate PDF</button>

@code {
    private async Task GeneratePdf()
    {
        var pdf = PdfService.GeneratePdf("Sample Title", "This is sample content for the PDF.");
        var base64 = Convert.ToBase64String(pdf);
        var url = $"data:application/pdf;base64,{base64}";
        await JS.InvokeVoidAsync("open", url, "_blank");
    }
}

This code converts the generated PDF into a Base64 string and opens it directly in the browser. This approach works for both Blazor WebAssembly and Blazor Server applications.


Benefits of Combining Blazor with PDFsharp and MigraDoc

  1. Full Control Over Document Structure: Using PDFsharp and MigraDoc, you can design highly customized documents, including multi-page reports, invoices, and dynamically generated content.
  2. Real-Time User Interaction: Blazor’s component model allows for real-time interactions with the UI, meaning users can quickly export data to PDFs based on their inputs or application state.
  3. Scalability with Blazor Server: For large and complex documents, Blazor Server allows for powerful server-side processing, which can handle intensive tasks such as rendering large PDFs or integrating data from databases.
  4. Cross-Platform Support: Whether you choose Blazor WebAssembly for client-side rendering or Blazor Server for heavy backend processing, you have flexibility in how you design and scale your application.

Conclusion

The BlazorSharpProject serves as a robust example of how to integrate Blazor, PDFsharp, and MigraDoc to create dynamic PDFs in a web application. The flexibility of Blazor combined with the document generation capabilities of PDFsharp and MigraDoc makes it an excellent choice for creating interactive, cross-platform web applications that require PDF export functionality.

With a unified C# environment and the power of .NET libraries, you can efficiently build, scale, and customize PDF generation in your Blazor applications, whether for simple reports or complex, dynamically generated documents.


Next Steps

  • Clone the project BlazorSharpProject to explore the code.
  • Experiment with PDFsharp and MigraDoc to create your own document templates and structures.
  • Consider extending the project by adding features such as database-driven PDF generation or multi-language support for international applications.
Discover and read more posts from Qaiser Mehmood
get started