フッターコンテンツにスキップ
IRONPDFの使用

BlazorでPDFを表示する方法(ガイド)

はじめに

Blazorの最新のウェブアプリケーションでPDF機能を表示するには、基本的なブラウザーの機能を超えた強力なPDFビューアーコンポーネントが必要です。 .NETの開発者がBlazorアプリケーションを構築する際、IronPDFは、Blazor Serverアプリとシームレスに統合する強力なPDFビューアーソリューションを提供します。 これにより、サードパーティのブラウザーツールに頼ることなく、高性能で豊富な機能を備えたPDFドキュメントを表示できます。

このチュートリアルでは、IronPDFを使用してBlazor PDFビューアーを実装する方法を探り、PDFファイルを開くことができ、PDFコンテンツを処理し、デスクトップと携帯電話の両方でPDFを表示するための直感的なインターフェースを提供するPDFビューアーコンポーネントを作成します。

IronPDFでPDFの表示を開始する

Blazor PDFビューアーを実装する前に、IronPDFをインストールする必要があります。 NuGetを通じて、Blazor Serverアプリにそれを追加します:

Install-Package IronPdf

次に、新しいBlazorアプリケーションを作成し、最新の.NET Coreがインストールされていることを確認します。 PDFファイルをwwwrootフォルダに保管して簡単にアクセスできるようにするか、バイト配列やURLなど他のソースからロードする準備をします。

最初のBlazor PDFビューアーコンポーネントを作成する

PDFドキュメントを表示できる基本的なBlazor PDFビューアーコンポーネントを作りましょう。 まず、新しいRazorコンポーネントを作成します:

@page "/pdfviewer"
@rendermode InteractiveServer
@using IronPdf
@inject IJSRuntime JSRuntime
@inject Microsoft.AspNetCore.Hosting.IWebHostEnvironment WebHostEnvironment
<h3>PDF Viewer Component</h3>
<div>
    <button @onclick="LoadPdfDocument">Open File</button>
    <div id="pdfContainer">
        @if (!string.IsNullOrEmpty(pdfUrl))
        {
            <iframe src="@pdfUrl" style="width:100%; height:600px;"></iframe>
        }
    </div>
</div>
@code {
    private string pdfUrl = "";
    private byte[] pdfData;
    private async Task LoadPdfDocument()
    {
        // Load PDF from file
        var pdfDocument = PdfDocument.FromFile("wwwroot/sample.pdf");
        pdfData = pdfDocument.BinaryData;
        // Create object URL for display
        pdfUrl = await CreateObjectUrl(pdfData);
    }
    private async Task<string> CreateObjectUrl(byte[] data)
    {
        var base64 = Convert.ToBase64String(data);
        return $"data:application/pdf;base64,{base64}";
    }
}
@page "/pdfviewer"
@rendermode InteractiveServer
@using IronPdf
@inject IJSRuntime JSRuntime
@inject Microsoft.AspNetCore.Hosting.IWebHostEnvironment WebHostEnvironment
<h3>PDF Viewer Component</h3>
<div>
    <button @onclick="LoadPdfDocument">Open File</button>
    <div id="pdfContainer">
        @if (!string.IsNullOrEmpty(pdfUrl))
        {
            <iframe src="@pdfUrl" style="width:100%; height:600px;"></iframe>
        }
    </div>
</div>
@code {
    private string pdfUrl = "";
    private byte[] pdfData;
    private async Task LoadPdfDocument()
    {
        // Load PDF from file
        var pdfDocument = PdfDocument.FromFile("wwwroot/sample.pdf");
        pdfData = pdfDocument.BinaryData;
        // Create object URL for display
        pdfUrl = await CreateObjectUrl(pdfData);
    }
    private async Task<string> CreateObjectUrl(byte[] data)
    {
        var base64 = Convert.ToBase64String(data);
        return $"data:application/pdf;base64,{base64}";
    }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

このコードは、PDFドキュメントを読み込み、iframeを使用して表示するシンプルなPDFビューアーコンポーネントを作成します。 LoadPdfDocumentメソッドは、同じパス(wwwrootフォルダ)からPDFファイルを読み込み、それをバイト配列に変換します。 CreateObjectUrlメソッドはこのバイト配列をデータURLに変換し、iframeが表示できるようにし、ユーザーが簡単に読み込んだPDFドキュメントを表示できるようにします。

出力

BlazorでPDFを表示する方法(ガイド): 図1

強化された表示のためのJavaScript相互運用の実装

PDFコンテンツの表示をより良く制御するために、JavaScript関数を使用してPDFビューアーの機能を処理できます:

@page "/pdf-jsinterop"
@rendermode InteractiveServer
@using IronPdf
@inject IJSRuntime JSRuntime
@inject Microsoft.AspNetCore.Hosting.IWebHostEnvironment WebHostEnvironment
<h3>IronPDF JavaScript Interop Viewer</h3>
<p>Displays PDF using JavaScript's Blob/ObjectURL capabilities.</p>
@if (!string.IsNullOrEmpty(ErrorMessage))
{
    <div class="alert alert-danger">Error: @ErrorMessage</div>
}
<div id="@documentId" style="border: 1px solid #ccc; width: 100%; min-height: 600px;">
    Loading PDF...
</div>
@code {
    private string documentId = Guid.NewGuid().ToString();
    private string ErrorMessage = string.Empty;
    private bool pdfLoaded = false;
    // Hold the reference to the loaded JavaScript module
    private IJSObjectReference? jsModule;
    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender && !pdfLoaded)
        {
            try
            {
                // 1. Asynchronously load the JavaScript file as a module
                // This guarantees the script is loaded before the next line executes.
                jsModule = await JSRuntime.InvokeAsync<IJSObjectReference>("import",
                    "./pdfViewerInterop.js");
                await LoadPdfWithJavaScript();
                pdfLoaded = true;
            }
            catch (Exception ex)
            {
                ErrorMessage = $"Failed to load JS module or execute: {ex.Message}";
            }
            finally
            {
                StateHasChanged();
            }
        }
    }
    private async Task LoadPdfWithJavaScript()
    {
        if (jsModule is null) return; // Should never happen if the module loads successfully
        try
        {
            var pdfPath = Path.Combine(WebHostEnvironment.WebRootPath, "sample.pdf");
            if (!File.Exists(pdfPath))
            {
                ErrorMessage = $"File not found: {pdfPath}";
                return;
            }
            var pdf = PdfDocument.FromFile(pdfPath);
            var stream = new MemoryStream(pdf.BinaryData);
            // 2. Invoke the function using the module reference
            // Note: We only pass the function name here.
            await jsModule.InvokeVoidAsync("displayPdf",
                documentId, stream.ToArray());
        }
        catch (Exception ex)
        {
            ErrorMessage = $"Failed to load PDF or invoke JS: {ex.Message}";
        }
    }
    // IMPORTANT: Dispose of the module when the component is removed
    public async ValueTask DisposeAsync()
    {
        if (jsModule is not null)
        {
            await jsModule.DisposeAsync();
        }
    }
}
@page "/pdf-jsinterop"
@rendermode InteractiveServer
@using IronPdf
@inject IJSRuntime JSRuntime
@inject Microsoft.AspNetCore.Hosting.IWebHostEnvironment WebHostEnvironment
<h3>IronPDF JavaScript Interop Viewer</h3>
<p>Displays PDF using JavaScript's Blob/ObjectURL capabilities.</p>
@if (!string.IsNullOrEmpty(ErrorMessage))
{
    <div class="alert alert-danger">Error: @ErrorMessage</div>
}
<div id="@documentId" style="border: 1px solid #ccc; width: 100%; min-height: 600px;">
    Loading PDF...
</div>
@code {
    private string documentId = Guid.NewGuid().ToString();
    private string ErrorMessage = string.Empty;
    private bool pdfLoaded = false;
    // Hold the reference to the loaded JavaScript module
    private IJSObjectReference? jsModule;
    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender && !pdfLoaded)
        {
            try
            {
                // 1. Asynchronously load the JavaScript file as a module
                // This guarantees the script is loaded before the next line executes.
                jsModule = await JSRuntime.InvokeAsync<IJSObjectReference>("import",
                    "./pdfViewerInterop.js");
                await LoadPdfWithJavaScript();
                pdfLoaded = true;
            }
            catch (Exception ex)
            {
                ErrorMessage = $"Failed to load JS module or execute: {ex.Message}";
            }
            finally
            {
                StateHasChanged();
            }
        }
    }
    private async Task LoadPdfWithJavaScript()
    {
        if (jsModule is null) return; // Should never happen if the module loads successfully
        try
        {
            var pdfPath = Path.Combine(WebHostEnvironment.WebRootPath, "sample.pdf");
            if (!File.Exists(pdfPath))
            {
                ErrorMessage = $"File not found: {pdfPath}";
                return;
            }
            var pdf = PdfDocument.FromFile(pdfPath);
            var stream = new MemoryStream(pdf.BinaryData);
            // 2. Invoke the function using the module reference
            // Note: We only pass the function name here.
            await jsModule.InvokeVoidAsync("displayPdf",
                documentId, stream.ToArray());
        }
        catch (Exception ex)
        {
            ErrorMessage = $"Failed to load PDF or invoke JS: {ex.Message}";
        }
    }
    // IMPORTANT: Dispose of the module when the component is removed
    public async ValueTask DisposeAsync()
    {
        if (jsModule is not null)
        {
            await jsModule.DisposeAsync();
        }
    }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

このJavaScript関数をwwwrootフォルダのJavaScriptファイルに追加します:

export function displayPdf(elementId, data) {
    // 1. Create a Blob from the byte array data
    const blob = new Blob([new Uint8Array(data)],
        { type: 'application/pdf' });
    // 2. Create a temporary URL for the Blob
    const url = URL.createObjectURL(blob);
    // 3. Find the container element
    const container = document.getElementById(elementId);
    if (!container) return;
    // 4. Clear any previous content
    container.innerHTML = '';
    // 5. Create and configure the iframe
    const iframe = document.createElement('iframe');
    iframe.src = url;
    iframe.style.width = '100%';
    iframe.style.height = '600px';
    iframe.style.border = 'none';
    // 6. Append the iframe to the container
    container.appendChild(iframe);
}
export function displayPdf(elementId, data) {
    // 1. Create a Blob from the byte array data
    const blob = new Blob([new Uint8Array(data)],
        { type: 'application/pdf' });
    // 2. Create a temporary URL for the Blob
    const url = URL.createObjectURL(blob);
    // 3. Find the container element
    const container = document.getElementById(elementId);
    if (!container) return;
    // 4. Clear any previous content
    container.innerHTML = '';
    // 5. Create and configure the iframe
    const iframe = document.createElement('iframe');
    iframe.src = url;
    iframe.style.width = '100%';
    iframe.style.height = '600px';
    iframe.style.border = 'none';
    // 6. Append the iframe to the container
    container.appendChild(iframe);
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

このJavaScript関数は、PDFデータからブロブを作成し、オブジェクトURLを生成します。 それから動的にiframe要素を作成し、コンテナーに追加します。 このアプローチは、PDFページの表示をどのように制御するかについてのコントロールを提供し、PDFビューアーコンポーネントのライフサイクルをより適切に扱うことを可能にします。

出力

BlazorでPDFを表示する方法(ガイド): 図2 - JavaScript PDFビューアー

異なるソースからのPDFファイルの読み込み

あなたのBlazor PDFビューアーは、さまざまなソースからPDFドキュメントを取得し表示できる:

private async Task LoadFromUrl()
{
    var client = new HttpClient();
    var response = await client.GetAsync("https://example.com/file.pdf");
    var stream = await response.Content.ReadAsStreamAsync();
    var pdfDocument = new PdfDocument(stream);
    await DisplayPdfContent(pdfDocument);
}
private async Task LoadFromHtmlContent()
{
    var renderer = new ChromePdfRenderer();
    var htmlContent = "<h1>Generated PDF</h1>";
    var pdfDocument = renderer.RenderHtmlAsPdf(htmlContent);
    await DisplayPdfContent(pdfDocument);
}
private async Task DisplayPdfContent(PdfDocument document)
{
    var data = document.BinaryData;
    pdfUrl = $"data:application/pdf;base64,{Convert.ToBase64String(data)}";
}
private async Task LoadFromUrl()
{
    var client = new HttpClient();
    var response = await client.GetAsync("https://example.com/file.pdf");
    var stream = await response.Content.ReadAsStreamAsync();
    var pdfDocument = new PdfDocument(stream);
    await DisplayPdfContent(pdfDocument);
}
private async Task LoadFromHtmlContent()
{
    var renderer = new ChromePdfRenderer();
    var htmlContent = "<h1>Generated PDF</h1>";
    var pdfDocument = renderer.RenderHtmlAsPdf(htmlContent);
    await DisplayPdfContent(pdfDocument);
}
private async Task DisplayPdfContent(PdfDocument document)
{
    var data = document.BinaryData;
    pdfUrl = $"data:application/pdf;base64,{Convert.ToBase64String(data)}";
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

これらの方法は、HTTPSを使用してURLからPDFファイルを読み込み、HTMLコンテンツをPDFに変換し、結果のPDFコンテンツを表示する方法を示しています。 LoadFromUrlメソッドはリモートの場所からPDFドキュメントを取得し、LoadFromHtmlContentは飛び込みでHTMLをPDFに変換する方法を示し、Blazor PDFビューアーコンポーネントがそのコンテンツをどのように調達するかについての柔軟性を提供します。

HTMLコンテンツを使用した出力

BlazorでPDFを表示する方法(ガイド): 図3 - HTMLから生成されて表示されたPDF

インタラクティブ機能の追加

インタラクティブな機能であなたのPDFビューアーを強化する:

@code {
    private int currentPage = 1;
    private int totalPages;
    private string rotationClass = "";
    private async Task NavigateToPage(int page)
    {
        currentPage = page;
        await JSRuntime.InvokeVoidAsync("navigateTo", page);
    }
    private void RotateCounterclockwise()
    {
        // Counterclockwise switch orientation
        rotationClass = "rotate-270";
    }
    private async Task PrintPdf()
    {
        await JSRuntime.InvokeVoidAsync("printDocument", documentId);
    }
    private async Task DownloadPdf()
    {
        var fileName = "document.pdf";
        await JSRuntime.InvokeVoidAsync("downloadFile", 
           pdfData, fileName);
    }
}
@code {
    private int currentPage = 1;
    private int totalPages;
    private string rotationClass = "";
    private async Task NavigateToPage(int page)
    {
        currentPage = page;
        await JSRuntime.InvokeVoidAsync("navigateTo", page);
    }
    private void RotateCounterclockwise()
    {
        // Counterclockwise switch orientation
        rotationClass = "rotate-270";
    }
    private async Task PrintPdf()
    {
        await JSRuntime.InvokeVoidAsync("printDocument", documentId);
    }
    private async Task DownloadPdf()
    {
        var fileName = "document.pdf";
        await JSRuntime.InvokeVoidAsync("downloadFile", 
           pdfData, fileName);
    }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

このコードは、PDFページ間のナビゲーション、回転機能(反時計方向回転も含む)、PDFの印刷機能を追加します。 ダウンロード機能は、ユーザーがPDFファイルをローカルに保存できるようにします。 これらの機能は基本的なPDFビューアーを強力なPDFビューアーに変え、ユーザーがPDFドキュメントを操作するために必要な基本的な機能を備えた内蔵ツールバーを提供します。

出力

BlazorでPDFを表示する方法(ガイド):図4 - カスタムインタラクティブ機能を備えたPDFビューアー

PDFフォーム入力と注釈の処理

フォームフィールドや注釈があるPDFドキュメントについては、IronPDFが強力なサポートを提供します:

private async Task ProcessFormFields(
{
    var pdfDocument = PdfDocument.FromFile("form.pdf");
    foreach (var field in pdfDocument.Form.Fields)
    {
        if (field.Type == PdfFormFieldType.Text)
        {
            field.Value = "User Input";
        }
    }
    // Enable form filling in viewer
    var modifiedPdf = pdfDocument.BinaryData;
    await DisplayPdfContent(pdfDocument);
}
private async Task ProcessFormFields(
{
    var pdfDocument = PdfDocument.FromFile("form.pdf");
    foreach (var field in pdfDocument.Form.Fields)
    {
        if (field.Type == PdfFormFieldType.Text)
        {
            field.Value = "User Input";
        }
    }
    // Enable form filling in viewer
    var modifiedPdf = pdfDocument.BinaryData;
    await DisplayPdfContent(pdfDocument);
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

これにより、Blazor PDFビューアーコンポーネント内でフォーム入力機能を実現し、ユーザーはブラウザ内で直接フォームフィールドを操作できます。 コードはPDFドキュメントのフォームフィールドをループしてプログラム的に値を設定することができるため、動的フォーム入力を必要とするアプリケーションに最適です。

出力

BlazorでPDFを表示する方法(ガイド):図5 - フォーム入力を備えたPDF表示

パフォーマンスの最適化

特に大きなPDFファイルを表示する場合の高性能を保証するために:

private async Task LoadLargePdf()
{
    const int chunkSize = 1024 * 1024; // 1MB chunks
    var pdfPath = "largefile.pdf";
    using (var fileStream = File.OpenRead(pdfPath))
    {
        var buffer = new byte[chunkSize];
        var chunks = new List<byte[]>();
        int bytesRead;
        while ((bytesRead = await fileStream.ReadAsync(buffer)) > 0)
        {
            var chunk = new byte[bytesRead];
            Array.Copy(buffer, chunk, bytesRead);
            chunks.Add(chunk);
        }
        // Process chunks for display
        await ProcessPdfChunks(chunks);
    }
}
private async Task LoadLargePdf()
{
    const int chunkSize = 1024 * 1024; // 1MB chunks
    var pdfPath = "largefile.pdf";
    using (var fileStream = File.OpenRead(pdfPath))
    {
        var buffer = new byte[chunkSize];
        var chunks = new List<byte[]>();
        int bytesRead;
        while ((bytesRead = await fileStream.ReadAsync(buffer)) > 0)
        {
            var chunk = new byte[bytesRead];
            Array.Copy(buffer, chunk, bytesRead);
            chunks.Add(chunk);
        }
        // Process chunks for display
        await ProcessPdfChunks(chunks);
    }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

このアプローチは大きなPDFファイルをチャンクに分けて読み込み、メモリの問題を防ぎ、かなりのPDFドキュメントでもスムーズなパフォーマンスを確保します。 特に携帯電話やリソースの限られたデバイスでPDFファイルを扱う場合に便利です。

Blazorアプリケーションのためのセキュリティ考慮事項

パスワードで保護されたPDFファイルを扱う際に:

private async Task LoadSecurePdf(string password)
{
    var pdfDocument = PdfDocument.FromFile("secure.pdf", password);
    if (pdfDocument != null)
    {
       var headers = new Dictionary<string, string>
        {
            {"X-Frame-Options", "SAMEORIGIN"},
            {"Content-Security-Policy", "default-src 'self'"}
        };
        await DisplayPdfContent(pdfDocument);
    }
}
private async Task LoadSecurePdf(string password)
{
    var pdfDocument = PdfDocument.FromFile("secure.pdf", password);
    if (pdfDocument != null)
    {
       var headers = new Dictionary<string, string>
        {
            {"X-Frame-Options", "SAMEORIGIN"},
            {"Content-Security-Policy", "default-src 'self'"}
        };
        await DisplayPdfContent(pdfDocument);
    }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

このコードは、適切なヘッダー設定を通じてセキュリティを維持しながら、パスワード保護されたPDFドキュメントを読み込む方法を示しています。

結論

IronPDFを持つBlazor PDFビューアーの実装は、WebアプリケーションでPDFを表示するための総合的なソリューションを開発者に提供します。 基本的な表示からフォーム入力や注釈のような高度な機能に至るまで、IronPDFのPDFビューアーコンポーネントはプロフェッショナルなアプリケーションに必要な機能を提供します。

示された例は、さまざまなPDFソースを処理し、インタラクティブな機能を提供し、高性能を維持するロバストなBlazor PDFビューアーを作成する方法を示しています。 シンプルなドキュメントビューアーまたは複雑なドキュメント管理システムを構築するかにかかわらず、IronPDFのBlazor Serverアプリとの統合により、プロフェッショナルなPDFビューイング機能の実装が容易になります。

自分のPDFビューアーを実装する準備はできていますか? IronPDFの無料トライアルを始めて、Blazorアプリケーションで強力なPDFビューイングエクスペリエンスを作成するための完全なドキュメント、デモアプリケーション、および開発者サポートにアクセスしてください。

よくある質問

IronPDF を使用して Blazor アプリケーションで PDF をどのように表示できますか?

IronPDF は、Blazor アプリケーション内で PDF をレンダリングおよび表示できる包括的な API を提供します。IronPDF を統合することで、強力な PDF ビューア コンポーネントを簡単に実装できます。

Blazor PDFビューイングにIronPDFを使用する利点は何ですか?

Blazor PDF 表示で IronPDF を使用することで、フォーム フィールドの処理、インタラクティブ ビューアの作成、高品質な PDF のシームレスなレンダリングなどのメリットを享受できます。

Blazor で IronPDF を使用して PDF のフォームフィールドを処理できますか?

はい、IronPDFはBlazorアプリケーション内でPDF文書のフォームフィールドを処理および操作することを可能にし、インタラクティブ性とユーザーエンゲージメントを向上させます。

IronPDF を使用して Blazor でインタラクティブな PDF ビューアを作成できますか?

もちろんです。IronPDF は、フォーム処理や動的コンテンツ表示などの機能を可能にする、Blazor でインタラクティブな PDF ビューアを作成するためのツールを提供します。

IronPDF は Blazor の PDF 操作にどのような機能を提供しますか?

IronPDF には、PDF レンダリング、フォームフィールド処理、テキスト抽出、ページ操作などの機能があり、Blazor での PDF 操作において多用途の選択肢となります。

IronPDF は Blazor アプリケーションの PDF 表示体験をどのように向上させますか?

IronPDF は、スムーズなレンダリング、インタラクティブな機能、PDF ドキュメントの堅牢な処理を提供することで、Blazor アプリケーションでの PDF 表示体験を向上させます。

カーティス・チャウ
テクニカルライター

Curtis Chauは、カールトン大学でコンピュータサイエンスの学士号を取得し、Node.js、TypeScript、JavaScript、およびReactに精通したフロントエンド開発を専門としています。直感的で美しいユーザーインターフェースを作成することに情熱を持ち、Curtisは現代のフレームワークを用いた開発や、構造の良い視覚的に魅力的なマニュアルの作成を楽しんでいます。

開発以外にも、CurtisはIoT(Internet of Things)への強い関心を持ち、ハードウェアとソフトウェアの統合方法を模索しています。余暇には、ゲームをしたりDiscordボットを作成したりして、技術に対する愛情と創造性を組み合わせています。