Zum Fußzeileninhalt springen
IRONPDF NUTZEN

Wie man einen Blazor PDF-Viewer mit IronPDF erstellt

Creating a Blazor PDF viewer in Blazor Server applications is a common need for business applications that display invoices, reports, and documents in the browser. This guide explains how to set up a fully functional PDF viewer in Blazor using IronPDF. It allows you to generate, customize, and open PDF files within your Blazor project effortlessly.

Unlike third-party browser tools, IronPDF makes it easy to create a powerful PDF viewer with built-in tools like zoom, navigation, text selection, and printing. Developers can also add features such as form filling, annotations, and counterclockwise switch orientation for rotating loaded PDF documents.

Get started with IronPDF today and transform how your Blazor applications handle PDF documents.

How Do I Set Up IronPDF in a Blazor Server Project?

Getting started with IronPDF in your Blazor Server PDF viewer project requires just a few steps. First, install the IronPDF NuGet package using the Package Manager Console:

Install-Package IronPdf

Alternatively, you can use the NuGet Package Manager UI to search for "IronPdf" and select the latest version.

NuGet Mit NuGet installieren

PM >  Install-Package IronPdf

Schauen Sie sich IronPDF auf NuGet für eine schnelle Installation an. Mit über 10 Millionen Downloads transformiert es die PDF-Entwicklung mit C#. Sie können auch das DLL oder den Windows Installer herunterladen.

After installation, add your license key to the Program.cs file to unlock full functionality:

// Program.cs
IronPdf.License.LicenseKey = "YOUR-LICENSE-KEY-HERE";
// Program.cs
IronPdf.License.LicenseKey = "YOUR-LICENSE-KEY-HERE";
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

For development and testing, IronPDF works without a license key but adds a watermark to generated PDFs. You can get a free trial license to remove the watermark during development. IronPDF supports both Blazor Server and Blazor WebAssembly apps, so you can add PDF generation and viewing to desktop, mobile apps, or even .NET MAUI projects.

How Can I Display a PDF File from a URL in Blazor?

The most straightforward way to create a PDF viewer in Blazor is by converting a URL to a PDF and displaying it in an iframe. IronPDF's ChromePdfRenderer class handles the conversion using its Chrome rendering engine, maintaining all styling and JavaScript functionality from the original webpage.

Here's a complete Razor component that renders a URL as a PDF:

@page "/pdfviewer"
@using IronPdf
<h3>PDF Viewer</h3>
<button @onclick="GeneratePdf" class="btn btn-primary">Load PDF</button>
@if (!string.IsNullOrEmpty(pdfDataUri))
{
    <iframe src="@pdfDataUri" style="width:100%; height:600px; border:1px solid #ccc; margin-top:20px;"></iframe>
}
@code {
    private string pdfDataUri = string.Empty;
    private async Task GeneratePdf()
    {
        var renderer = new ChromePdfRenderer();
        // Convert URL to PDF
        var pdf = await renderer.RenderUrlAsPdfAsync("https://ironpdf.com");
        // Convert to base64 and create data URI for iframe display
        var base64String = Convert.ToBase64String(pdf.BinaryData);
        pdfDataUri = $"data:application/pdf;base64,{base64String}";
    }
}
@page "/pdfviewer"
@using IronPdf
<h3>PDF Viewer</h3>
<button @onclick="GeneratePdf" class="btn btn-primary">Load PDF</button>
@if (!string.IsNullOrEmpty(pdfDataUri))
{
    <iframe src="@pdfDataUri" style="width:100%; height:600px; border:1px solid #ccc; margin-top:20px;"></iframe>
}
@code {
    private string pdfDataUri = string.Empty;
    private async Task GeneratePdf()
    {
        var renderer = new ChromePdfRenderer();
        // Convert URL to PDF
        var pdf = await renderer.RenderUrlAsPdfAsync("https://ironpdf.com");
        // Convert to base64 and create data URI for iframe display
        var base64String = Convert.ToBase64String(pdf.BinaryData);
        pdfDataUri = $"data:application/pdf;base64,{base64String}";
    }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

The RenderUrlAsPdfAsync method fetches the webpage content, converts it into the PDF format, and renders it in your Blazor PDF viewer component. This approach works across desktop and mobile phones, with a built-in toolbar for navigating, zooming, and printing PDFs. The loaded PDF document should appear similar to how it is in the following output image:

How to Create a Blazor PDF Viewer Using IronPDF: Figure 1 - URL to PDF PDF viewer output

How Do I Customize PDF Generation?

IronPDF provides extensive customization options through the ChromePdfRenderOptions class for your Blazor PDF viewer component. You can add headers, footers, adjust margins, and control page layout to create professional-looking documents. Learn more about rendering options in the documentation.

@page "/pdfcustom"
@using IronPdf
<h3>Customized PDF Viewer</h3>
<button @onclick="GenerateCustomizedPdf" class="btn btn-primary">Generate Customized PDF</button>
@if (!string.IsNullOrEmpty(pdfDataUri))
{
    <iframe src="@pdfDataUri" style="width:100%; height:600px; border:1px solid #ccc; margin-top:20px;"></iframe>
}
@code {
    private string pdfDataUri = string.Empty;
    private async Task GenerateCustomizedPdf()
    {
        var renderer = new ChromePdfRenderer();
        // Assign rendering options to the renderer
        renderer.RenderingOptions = new ChromePdfRenderOptions
        {
            PaperSize = IronPdf.Rendering.PdfPaperSize.A4,
            MarginTop = 25,
            MarginBottom = 25,
            MarginLeft = 20,
            MarginRight = 20,
            // Add header with title
            TextHeader = new TextHeaderFooter
            {
                CenterText = "Monthly Report - {date}",
                FontSize = 12
            },
            // Add footer with page numbers
            TextFooter = new TextHeaderFooter
            {
                LeftText = "Confidential",
                RightText = "Page {page} of {total-pages}",
                FontSize = 10
            }
        };
        // Now generate with options applied
        var pdf = await renderer.RenderUrlAsPdfAsync("https://example.com/report");
        // Display in iframe
        pdfDataUri = $"data:application/pdf;base64,{Convert.ToBase64String(pdf.BinaryData)}";
    }
}
@page "/pdfcustom"
@using IronPdf
<h3>Customized PDF Viewer</h3>
<button @onclick="GenerateCustomizedPdf" class="btn btn-primary">Generate Customized PDF</button>
@if (!string.IsNullOrEmpty(pdfDataUri))
{
    <iframe src="@pdfDataUri" style="width:100%; height:600px; border:1px solid #ccc; margin-top:20px;"></iframe>
}
@code {
    private string pdfDataUri = string.Empty;
    private async Task GenerateCustomizedPdf()
    {
        var renderer = new ChromePdfRenderer();
        // Assign rendering options to the renderer
        renderer.RenderingOptions = new ChromePdfRenderOptions
        {
            PaperSize = IronPdf.Rendering.PdfPaperSize.A4,
            MarginTop = 25,
            MarginBottom = 25,
            MarginLeft = 20,
            MarginRight = 20,
            // Add header with title
            TextHeader = new TextHeaderFooter
            {
                CenterText = "Monthly Report - {date}",
                FontSize = 12
            },
            // Add footer with page numbers
            TextFooter = new TextHeaderFooter
            {
                LeftText = "Confidential",
                RightText = "Page {page} of {total-pages}",
                FontSize = 10
            }
        };
        // Now generate with options applied
        var pdf = await renderer.RenderUrlAsPdfAsync("https://example.com/report");
        // Display in iframe
        pdfDataUri = $"data:application/pdf;base64,{Convert.ToBase64String(pdf.BinaryData)}";
    }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

The template variables, such as {page}, {total-pages}, and {date}, are automatically replaced with actual values during PDF generation in your Blazor PDF viewer. You can also use the HtmlHeader and HtmlFooter properties for more complex layouts with HTML content. This ensures your Blazor PDF viewer can render high-performance documents with proper layout, branding, and form fields where needed. For detailed header and footer customization, see the headers and footers guide.

How to Create a Blazor PDF Viewer Using IronPDF: Figure 2 - Customized PDF opened in PDF viewer

What's the Best Way to Enable PDF Downloads?

While displaying PDFs in Blazor using an iframe works well for viewing, users often need to download the document. You can implement this using JavaScript InterOp to trigger a browser download. For more download options, see our export and save PDF guide:

@page "/pdfdownload"
@using IronPdf
@inject IJSRuntime JSRuntime
<h3>Download PDF</h3>
<button @onclick="DownloadPdf" class="btn btn-success">Download PDF</button>
@code {
    private async Task DownloadPdf()
    {
        var renderer = new ChromePdfRenderer();
        var pdf = await renderer.RenderHtmlAsPdfAsync("<h1>Invoice</h1><p>Total: $1,299</p>");
        using var streamRef = new DotNetStreamReference(stream: new MemoryStream(pdf.BinaryData));
        await JSRuntime.InvokeVoidAsync("downloadFileFromStream", "invoice.pdf", streamRef);
    }
}
@page "/pdfdownload"
@using IronPdf
@inject IJSRuntime JSRuntime
<h3>Download PDF</h3>
<button @onclick="DownloadPdf" class="btn btn-success">Download PDF</button>
@code {
    private async Task DownloadPdf()
    {
        var renderer = new ChromePdfRenderer();
        var pdf = await renderer.RenderHtmlAsPdfAsync("<h1>Invoice</h1><p>Total: $1,299</p>");
        using var streamRef = new DotNetStreamReference(stream: new MemoryStream(pdf.BinaryData));
        await JSRuntime.InvokeVoidAsync("downloadFileFromStream", "invoice.pdf", streamRef);
    }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

Add this JavaScript function to your _Host.cshtml file (as discussed in Microsoft's Blazor JavaScript InterOp documentation):

<script>
    window.downloadFileFromStream = async (fileName, contentStreamReference) => {
        const arrayBuffer = await contentStreamReference.arrayBuffer();
        const blob = new Blob([arrayBuffer]);
        const url = URL.createObjectURL(blob);
        const anchorElement = document.createElement('a');
        anchorElement.href = url;
        anchorElement.download = fileName ?? '';
        anchorElement.click();
        anchorElement.remove();
        URL.revokeObjectURL(url);
    }
</script>
<script>
    window.downloadFileFromStream = async (fileName, contentStreamReference) => {
        const arrayBuffer = await contentStreamReference.arrayBuffer();
        const blob = new Blob([arrayBuffer]);
        const url = URL.createObjectURL(blob);
        const anchorElement = document.createElement('a');
        anchorElement.href = url;
        anchorElement.download = fileName ?? '';
        anchorElement.click();
        anchorElement.remove();
        URL.revokeObjectURL(url);
    }
</script>
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

How Can I Generate PDFs from Razor Components?

One of the most powerful features for displaying PDFs in Blazor is generating PDFs directly from HTML content, including dynamic data. This approach is perfect for creating invoices, reports, or any data-driven documents. Check out our guide on HTML to PDF conversion for more advanced techniques:

@page "/invoicedemo"
@using IronPdf
<h3>Invoice Generator</h3>
<button @onclick="GenerateInvoice" class="btn btn-primary">Generate Invoice PDF</button>
@if (!string.IsNullOrEmpty(pdfDataUri))
{
    <iframe src="@pdfDataUri" style="width:100%; height:600px; border:1px solid #ccc; margin-top:20px;"></iframe>
}
@code {
    private string pdfDataUri = string.Empty;
    private async Task GenerateInvoice()
    {
        var invoiceHtml = $@"
            <html>
            <head>
                <style>
                    body {{ font-family: Arial, sans-serif; }}
                    .header {{ background-color: #f0f0f0; padding: 20px; }}
                    .invoice-table {{ width: 100%; border-collapse: collapse; }}
                    .invoice-table th, .invoice-table td {{ border: 1px solid #ddd; padding: 8px; }}
                    .total {{ font-weight: bold; font-size: 18px; }}
                </style>
            </head>
            <body>
                <div class='header'>
                    <h1>Invoice #INV-2024-001</h1>
                    <p>Date: {DateTime.Now:MM/dd/yyyy}</p>
                </div>
                <table class='invoice-table'>
                    <thead>
                        <tr>
                            <th>Item</th>
                            <th>Quantity</th>
                            <th>Price</th>
                            <th>Total</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr>
                            <td>IronPDF License</td>
                            <td>1</td>
                            <td>$799</td>
                            <td>$799</td>
                        </tr>
                        <tr>
                            <td>Priority Support</td>
                            <td>1</td>
                            <td>$250</td>
                            <td>$250</td>
                        </tr>
                    </tbody>
                </table>
                <p class='total'>Total Amount: $1,199</p>
            </body>
            </html>";
        var renderer = new ChromePdfRenderer();
        var pdf = await renderer.RenderHtmlAsPdfAsync(invoiceHtml);
        pdfDataUri = $"data:application/pdf;base64,{Convert.ToBase64String(pdf.BinaryData)}";
    }
}
@page "/invoicedemo"
@using IronPdf
<h3>Invoice Generator</h3>
<button @onclick="GenerateInvoice" class="btn btn-primary">Generate Invoice PDF</button>
@if (!string.IsNullOrEmpty(pdfDataUri))
{
    <iframe src="@pdfDataUri" style="width:100%; height:600px; border:1px solid #ccc; margin-top:20px;"></iframe>
}
@code {
    private string pdfDataUri = string.Empty;
    private async Task GenerateInvoice()
    {
        var invoiceHtml = $@"
            <html>
            <head>
                <style>
                    body {{ font-family: Arial, sans-serif; }}
                    .header {{ background-color: #f0f0f0; padding: 20px; }}
                    .invoice-table {{ width: 100%; border-collapse: collapse; }}
                    .invoice-table th, .invoice-table td {{ border: 1px solid #ddd; padding: 8px; }}
                    .total {{ font-weight: bold; font-size: 18px; }}
                </style>
            </head>
            <body>
                <div class='header'>
                    <h1>Invoice #INV-2024-001</h1>
                    <p>Date: {DateTime.Now:MM/dd/yyyy}</p>
                </div>
                <table class='invoice-table'>
                    <thead>
                        <tr>
                            <th>Item</th>
                            <th>Quantity</th>
                            <th>Price</th>
                            <th>Total</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr>
                            <td>IronPDF License</td>
                            <td>1</td>
                            <td>$799</td>
                            <td>$799</td>
                        </tr>
                        <tr>
                            <td>Priority Support</td>
                            <td>1</td>
                            <td>$250</td>
                            <td>$250</td>
                        </tr>
                    </tbody>
                </table>
                <p class='total'>Total Amount: $1,199</p>
            </body>
            </html>";
        var renderer = new ChromePdfRenderer();
        var pdf = await renderer.RenderHtmlAsPdfAsync(invoiceHtml);
        pdfDataUri = $"data:application/pdf;base64,{Convert.ToBase64String(pdf.BinaryData)}";
    }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

This method gives you complete control over the PDF content and styling in your Blazor PDF viewer, allowing you to create pixel-perfect documents from your application data. For more complex HTML rendering scenarios, explore our HTML to PDF tutorials.

How to Create a Blazor PDF Viewer Using IronPDF: Figure 3 - Invoice PDF in viewer

What Other PDF Operations Can I Perform?

IronPDF offers many other tools and extensions beyond basic viewing:

  • Merging PDF pages into a single document
  • Adding annotations and editing features
  • Applying password protection and security
  • Enabling upload and dynamically creating table reports

Each of these extends the overview of what’s possible in a Blazor PDF viewer component, giving developers complete control over data, project workflows, and example applications. For more detailed information on these features, check out the guides on merging PDFs, watermarking, and PDF security.

Conclusion

You now have the foundation for implementing a PDF viewer in your Blazor Server application using IronPDF. From basic URL rendering to dynamic component-based generation, IronPDF provides the tools needed to handle PDF requirements in modern web applications. For additional Blazor development resources, consider exploring Microsoft's official Blazor documentation.

The combination of IronPDF's Chrome rendering engine and Blazor's component model creates a powerful solution for generating and displaying professional PDF documents directly in the browser, eliminating the need for external PDF viewers or plugins.

Ready to implement PDF functionality in your Blazor application? Start your free trial to find the perfect fit for your project.

Häufig gestellte Fragen

Was ist ein Blazor PDF-Viewer?

Ein Blazor PDF-Viewer ist eine Komponente, die in Blazor Server-Anwendungen verwendet wird, um PDF-Dokumente wie Rechnungen, Berichte und andere Dateien direkt im Browser anzuzeigen.

Wie kann ich einen PDF-Viewer in einer Blazor-Anwendung implementieren?

Sie können einen PDF-Viewer in einer Blazor-Anwendung mit IronPDF implementieren, das es Ihnen ermöglicht, PDF-Dateien mühelos innerhalb Ihres Blazor-Projekts zu erzeugen, anzupassen und zu öffnen.

Warum sollte ich IronPDF für meinen Blazor PDF-Viewer verwenden?

IronPDF ist eine robuste Lösung zur Integration von PDF-Anzeigefähigkeiten in Blazor-Anwendungen, bietet einfache Erzeugung und Anpassung von PDF-Dateien, verbessert die Benutzererfahrung und optimiert die Dokumentenverarbeitung.

Was sind die Vorteile der Verwendung eines PDF-Viewers in Blazor-Anwendungen?

Die Verwendung eines PDF-Viewers in Blazor-Anwendungen verbessert die Benutzererfahrung, indem es den Nutzern ermöglicht, Dokumente direkt im Browser anzusehen. Es ist besonders nützlich für die Anzeige geschäftlicher Dokumente wie Rechnungen und Berichte.

Kann IronPDF die PDF-Erzeugung in Blazor-Anwendungen übernehmen?

Ja, IronPDF kann die PDF-Erzeugung in Blazor-Anwendungen übernehmen, was die nahtlose Erstellung und Anpassung von PDF-Dokumenten zur Erfüllung verschiedener Geschäftsanforderungen ermöglicht.

Ist es möglich, PDF-Dateien mit IronPDF in Blazor anzupassen?

Absolut, IronPDF bietet umfangreiche Anpassungsmöglichkeiten für PDF-Dateien in Blazor-Anwendungen, sodass Entwickler Dokumente nach spezifischen Anforderungen gestalten können.

Welche Arten von Dokumenten können mit einem Blazor PDF-Viewer angezeigt werden?

Ein Blazor PDF-Viewer kann eine Vielzahl von Dokumenten anzeigen, einschließlich Rechnungen, Berichte und jedes andere Dokument, das in ein PDF-Format konvertiert werden kann.

Unterstützt IronPDF das Öffnen von PDF-Dateien in Blazor-Projekten?

Ja, IronPDF unterstützt das Öffnen von PDF-Dateien innerhalb von Blazor-Projekten, was es einfach macht, PDF-Dokumente direkt im Browser anzusehen und zu verwalten.

Wie ist die Benutzererfahrung mit einem Blazor PDF-Viewer?

Die Benutzererfahrung mit einem Blazor PDF-Viewer ist verbessert, da Benutzer PDF-Dokumente innerhalb ihres Webbrowsers einfach anzeigen und interagieren können, was einen nahtlosen und effizienten Dokumentenverarbeitungsprozess bietet.

Ist IronPDF mit .NET 10 für Blazor PDF-Viewer-Projekte kompatibel?

Ja – IronPDF ist vollständig kompatibel mit .NET 10. Es unterstützt alle aktuellen .NET-Versionen (10, 9, 8, 7, 6, Core, Framework) und funktioniert in Blazor-Webanwendungen unter .NET 10 ohne dass eine spezielle Konfiguration erforderlich ist.

Curtis Chau
Technischer Autor

Curtis Chau hat einen Bachelor-Abschluss in Informatik von der Carleton University und ist spezialisiert auf Frontend-Entwicklung mit Expertise in Node.js, TypeScript, JavaScript und React. Leidenschaftlich widmet er sich der Erstellung intuitiver und ästhetisch ansprechender Benutzerschnittstellen und arbeitet gerne mit modernen Frameworks sowie der Erstellung gut strukturierter, optisch ansprechender ...

Weiterlesen