Saltar al pie de página
.NET AYUDA

Aplicaciones Híbridas de Blazor (Cómo Funciona para Desarrolladores)

A .NET MAUI Blazor Hybrid app combines the cross-platform capabilities of .NET MAUI with the web development skills/capabilities of Blazor to create applications that can run natively on multiple platforms while sharing code and logic across them. This Blazor hybrid approach provides developers with flexibility, productivity, and the ability to reach a wider audience with their applications. A web developer can seamlessly create emulated mobile device apps with ease using web UI components. In this article, we will build a simple .NET MAUI Blazor Hybrid app using Visual Studio and also later see the IronPDF library overview from Iron Software's PDF Solutions to generate PDF documents.

How to Create .NET MAUI Blazor App to Generate PDF from a Website

  1. Create a new .NET MAUI Blazor Hybrid Project in Visual Studio
  2. Add IronPDF library to Generate PDF from Website URL
  3. Add code to Generate PDF using the IronPDF library

What is the .NET MAUI Blazor Hybrid App?

.NET MAUI Blazor app refers to an application built using .NET Multi-platform App UI (MAUI) and Blazor technologies. Let's break down these components:

.NET MAUI (Multi-platform App UI)

.NET MAUI is a framework for building cross-platform applications using .NET technologies and C#. It allows developers to write code once and deploy it on multiple platforms, including Windows, macOS, iOS mobile apps, and Android. .NET MAUI provides a single project structure and a unified API surface for developing applications across different platforms. It supports various UI components/elements, including controls, layouts, and navigation patterns, to create modern and responsive applications.

Blazor

Blazor is a web framework from Microsoft which allows developers to build interactive web development applications using C#. Blazor enables developers to write code that runs on the client side within the browser, as well as on the server side. Blazor applications can be developed using Razor syntax, which combines HTML markup with C# code, and they can leverage the power of .NET libraries and frameworks.

Hybrid App

A hybrid app combines elements of both native and web applications. In the context of .NET MAUI and Blazor, a hybrid app typically refers to an application that runs natively on various platforms (such as Windows, macOS, iOS, and Android) while also utilizing technologies (such as Blazor for UI rendering and business logic). This approach allows developers to leverage their existing skills in .NET and C# to build cross-platform applications that can take advantage of both native capabilities and web technologies.

Features of .NET MAUI Blazor Hybrid Apps

Cross-Platform Support

You can build your MAUI Blazor app once and deploy it across various devices without significant modifications. Blazor apps work as native apps for both Android and Apple devices.

.NET MAUI is engineered to provide robust support to create cross-platform apps in .NET technologies, encompassing Android, iOS, Windows, and macOS. This allows developers to create applications that seamlessly run on a wide array of devices without the need for significant modifications. A Blazor mobile app developed with .NET MAUI will behave like a native app on both Android and Apple devices.

Code and Component Sharing

One of the key advantages of .NET MAUI is its capability for code and UI components sharing across various platforms. This feature significantly reduces development time and effort, eliminating the necessity to rewrite code for each platform-specific feature. By sharing code and components, developers can streamline the development process and enhance code maintainability.

Native UI Controls

.NET MAUI Blazor Hybrid apps leverage native UI controls, ensuring a consistent and familiar user experience across different platforms. This allows developers to access platform-specific UI elements while maintaining a unified look and feel across all supported devices. By leveraging native UI controls or Web UI components, developers can create applications that feel native to each platform while maximizing code reuse.

Integration with Visual Studio

Visual Studio offers comprehensive tooling support for .NET MAUI development, empowering developers with a rich set of features for building, debugging, and managing their applications. With Visual Studio, developers can leverage familiar tools such as IntelliSense, debugging capabilities, and project management functionalities, enhancing productivity and efficiency throughout the development lifecycle.

Improved Performance

.NET MAUI Blazor Hybrid apps deliver enhanced performance compared to some other cross-platform solutions. The integration of Blazor and .NET MAUI ensures efficient execution of code, resulting in responsive and performant applications. By leveraging the power of the .NET runtime and native platform capabilities, developers can create applications that deliver a smooth and fluid user experience across various devices.

Hot Reload Support

.NET MAUI offers support for hot reload, allowing developers to instantly see changes during the development process without the need for recompilation or redeployment. This feature accelerates the development cycle, enabling developers to iterate quickly and efficiently. With hot reload support, developers can make real-time adjustments to their applications, accelerating the development process and improving overall productivity.

Advantages of Blazor Hybrid Apps with .NET MAUI

Single Codebase

Blazor Hybrid Apps with .NET MAUI enable developers to write their application's business logic and UI elements just once using C# and Blazor. This single codebase can then be deployed to multiple platforms without the need for extensive platform-specific adjustments, reducing development complexity and effort.

Reduced Development Time

By sharing code and components across platforms, developers can significantly reduce the time spent on development. Changes made in one place are reflected across all supported platforms, eliminating the need to write and maintain separate codebases for each platform. This streamlined development process translates into faster time-to-market and reduced development costs.

Maintenance Efficiency

With a single codebase for all platforms, maintenance becomes more straightforward and efficient. Bug fixes, updates, and enhancements can be applied uniformly to all supported platforms, ensuring consistency and reliability across the entire application. This simplifies the maintenance process and reduces the risk of introducing inconsistencies or errors across different versions of the application.

Access to Native APIs

Despite being based on web technologies, Blazor Hybrid Apps with .NET MAUI retain the capability to access native APIs when needed. This allows developers to leverage platform-specific features and functionalities seamlessly within their applications, providing a bridge between the capabilities of web-based frameworks and the native capabilities of each platform. By combining the power of Blazor with access to native APIs, developers can create feature-rich and versatile applications that cater to the unique requirements of each platform.

In summary, .NET MAUI Blazor Hybrid apps offer a seamless blend of web and native capabilities, making them efficient, easy to maintain, and suitable for cross-platform development.

Introducing IronPDF

Explore the IronPDF Library from Iron Software's PDF Solutions is a versatile library in the .NET world to generate, modify, and read PDF documents. IronPDF is a versatile cross-platform library that allows developers to create, edit, and sign PDF documents from various sources. Whether you’re working with HTML, images, or other document formats, IronPDF provides a comprehensive set of features for handling PDFs. Here are some key points about IronPDF:

  1. HTML to PDF Conversion:

    IronPDF can convert HTML content (including CSS, images, and JavaScript) into PDF documents. You can render web pages, Razor views (Blazor Server), CSHTML (MVC), ASPX (WebForms), and XAML (MAUI) as PDFs.

  2. Pixel-Perfect Rendering:

    IronPDF ensures accurate rendering, maintaining the visual fidelity of your content. It supports UTF-8 character encoding, base URLs, asset encoding, and TLS website logins.

  3. Page Templates and Settings:

    Customize your PDFs by adding headers, footers, page numbers, and page breaks. Set responsive layouts, custom paper sizes, orientations, and color options.

  4. Editing and Annotations:

    Edit PDF metadata, sign documents, and apply digital signatures. Merge, split, add, copy, and delete pages within PDFs. Add annotations and form fields.

  5. Cross-Platform Support:

    IronPDF works on various platforms: .NET Core (8, 7, 6, 5, and 3.1+), .NET Standard (2.0+), .NET Framework (4.6.2+). It’s compatible with Windows, Linux, and macOS.

Step 1: Create a New .NET MAUI Blazor Hybrid Project in Visual Studio

Start as below by selecting Create New Project in Visual Studio and select .NET MAUI Blazor Hybrid App project template.

Blazor Hybrid Apps (How It Works For Developers): Figure 1 - .NET MAUI Blazor Hybrid App Template

Provide the project name and location details.

Blazor Hybrid Apps (How It Works For Developers): Figure 2 - Project Configuration

Select the required .NET version. Click Create.

Blazor Hybrid Apps (How It Works For Developers): Figure 3 - Target Framework

Step 2: Add IronPDF library to Generate PDF from the Website URL

IronPDF library can be installed using a Visual Studio package manager like below.

Blazor Hybrid Apps (How It Works For Developers): Figure 4 - IronPDF

Also, it can be installed from NuGet Gallery.

Blazor Hybrid Apps (How It Works For Developers): Figure 5 - NuGet Gallery

dotnet add package IronPdf --version 2024.4.2

Step 3: Add Code to Generate PDF using IronPDF

Add the below code to the Home page to modify the existing autogenerated code to take URL input from the user and generate PDF documents.

@page "/"
@using IronPdf

<h1>Welcome to PDF Generator from Website URL</h1>
<p>Enter the Website URL to Generate PDF</p>
<input type="text" @bind="InputValue" placeholder="Enter URL" />
<p>Click to Generate PDF</p>
<button class="btn btn-primary" @onclick="GeneratePdf">Generate</button>

@code {
    // This property is bound to the input field for the user to enter the website URL
    private string? InputValue { get; set; }

    // This method is invoked when the "Generate" button is clicked
    // It uses IronPdf to generate a PDF from the URL entered by the user
    private void GeneratePdf()
    {
        // Check if the input value is not null or empty
        if (!string.IsNullOrWhiteSpace(InputValue))
        {
            // Render the URL as a PDF document
            var pdfDocument = HtmlToPdf.StaticRenderUrlAsPdf(InputValue);

            // Save the rendered PDF document to the specified location on the disk
            pdfDocument.SaveAs("C:\\temp\\output.pdf");
        }
    }
}

Code Explanation

Here we are receiving the input from the user using a text input. They have a button to trigger the PDF generation. HtmlToPdf.StaticRenderUrlAsPdf static method is used to generate the PDF document. We ensure that the input is not null or empty before proceeding with the PDF generation, thereby adding a basic validation to the input.

When we run the application, we can see the below UI.

Blazor Hybrid Apps (How It Works For Developers): Figure 6 - PDF Generator UI

Output

Blazor Hybrid Apps (How It Works For Developers): Figure 7 - PDF Output

Licensing (Free Trial Offer)

A valid license key is necessary for IronPDF, place this into the appsettings.json file as follows:

{
  "IronPdf.LicenseKey": "your license key"
}

A free trial license key can be obtained by registering for a trial license using IronPDF's trial license registration page.

Conclusion

Building a .NET MAUI Blazor Hybrid app offers a compelling solution for developers seeking to create cross-platform applications with the combined strengths of .NET MAUI and Blazor technologies. With robust cross-platform support, seamless code and component sharing, access to native UI controls, integration with Visual Studio, and enhanced performance, .NET MAUI Blazor Hybrid apps provide developers with the tools and capabilities needed to build modern, responsive, and feature-rich applications that run natively on various devices.

On the other hand, IronPDF is a tailor-made solution for generating PDF documents across multiple platforms like .NET MAUI Blazor Hybrid apps.

In summary, building a .NET MAUI Blazor Hybrid app and IronPDF enables developers to deliver high-quality applications that offer a consistent user experience across different platforms, while also benefiting from the productivity and flexibility of the .NET and Blazor ecosystems.

Preguntas Frecuentes

¿Cuál es el propósito de una aplicación híbrida .NET MAUI Blazor?

Una aplicación híbrida .NET MAUI Blazor permite a los desarrolladores construir aplicaciones con código y lógica compartidos que funcionan de manera nativa en múltiples plataformas, aprovechando tanto las capacidades multiplataforma de .NET MAUI como las fortalezas de desarrollo web de Blazor.

¿Cómo se pueden generar documentos PDF en una aplicación .NET MAUI Blazor?

Puedes generar documentos PDF en una aplicación .NET MAUI Blazor integrando la biblioteca IronPDF, que admite conversión de HTML a PDF, edición y renderizado en diferentes plataformas.

¿Cuáles son los pasos para crear una aplicación híbrida .NET MAUI Blazor usando Visual Studio?

Para crear una aplicación híbrida .NET MAUI Blazor, abre Visual Studio, selecciona la plantilla de Aplicación Híbrida .NET MAUI Blazor, configura la configuración del proyecto, selecciona la versión de .NET deseada e inicia el entorno del proyecto.

¿Cómo mejora la biblioteca IronPDF las funcionalidades de PDF en aplicaciones Blazor?

La biblioteca IronPDF mejora las funcionalidades de PDF al permitir a los desarrolladores convertir HTML a PDF, editar PDFs y renderizarlos con precisión. Admite el uso multiplataforma, lo que la hace ideal para aplicaciones .NET MAUI Blazor.

¿Cuál es la ventaja de usar .NET MAUI para el desarrollo multiplataforma?

.NET MAUI ofrece la ventaja de escribir código una vez y desplegarlo en múltiples plataformas, como Windows, macOS, iOS y Android, con acceso a APIs nativas y controles de UI para una experiencia de usuario consistente.

¿Cómo se añade la biblioteca IronPDF a una aplicación .NET MAUI Blazor?

La biblioteca IronPDF se puede añadir a una aplicación .NET MAUI Blazor mediante el gestor de paquetes de Visual Studio o ejecutando el comando dotnet add package IronPdf --version 2024.4.2 desde la Galería de NuGet.

¿Qué beneficios ofrece el enfoque híbrido para el desarrollo de aplicaciones?

El enfoque híbrido permite reducir el tiempo de desarrollo, compartir código y componentes, y acceder a APIs nativas, proporcionando una experiencia de usuario fluida a través de diferentes plataformas con controles de UI nativos y rendimiento mejorado.

¿Por qué es beneficioso usar IronPDF para desarrolladores que trabajan con PDFs en aplicaciones Blazor?

IronPDF es beneficioso porque ofrece herramientas robustas para generar, modificar y leer PDFs, incluyendo soporte para la conversión de HTML a PDF y renderizado perfecto en píxeles, mejorando las capacidades de las aplicaciones Blazor.

¿Qué papel juega Blazor en las aplicaciones híbridas .NET MAUI Blazor?

Blazor permite a los desarrolladores construir aplicaciones web interactivas utilizando C#, permitiendo que el código se ejecute tanto en el lado del cliente como del servidor, e integrándose con las bibliotecas .NET para mejorar el desarrollo en aplicaciones híbridas .NET MAUI Blazor.

¿Cómo mejora la productividad de desarrollo el enfoque híbrido .NET MAUI Blazor?

El enfoque híbrido .NET MAUI Blazor mejora la productividad al permitir a los desarrolladores escribir código compartido para múltiples plataformas, utilizar controles de UI nativos y aprovechar la recarga en caliente para ajustes en tiempo real sin recompilación.

Curtis Chau
Escritor Técnico

Curtis Chau tiene una licenciatura en Ciencias de la Computación (Carleton University) y se especializa en el desarrollo front-end con experiencia en Node.js, TypeScript, JavaScript y React. Apasionado por crear interfaces de usuario intuitivas y estéticamente agradables, disfruta trabajando con frameworks modernos y creando manuales bien ...

Leer más