使用IronPDF在C#中將PDF轉換為字節陣列
在新的瀏覽器分頁中開啟PDF文件是Blazor網頁應用程式中的一項常見需求。 本教程演示了如何使用IronPDF生成PDF,並使用JavaScript互操作在新分頁中顯示它們,為使用者提供無縫的文件查看體驗。 本範例專注於Blazor Server版本。
先決條件和設置
首先在Visual Studio 2022中建立一個新的Blazor Server專案。通過NuGet套件管理器控制台安裝IronPDF:
Install-Package IronPdf
在Program.cs中配置您的IronPDF授權以啟用完整功能:
License.LicenseKey = "YOUR-LICENSE-KEY";
License.LicenseKey = "YOUR-LICENSE-KEY";
License.LicenseKey = "YOUR-LICENSE-KEY"
了解挑戰
Blazor Server應用程式無法直接從伺服器上的C#程式碼操縱瀏覽器分頁。 Blazor開啟新分頁PDF的任務需要JavaScript互操作(JS互操作)來橋接伺服器端PDF生成和客戶端窗口管理。
IronPDF使開發人員能夠在伺服器上生成高質量的PDF文件,然後可以使用JavaScript的window.open()功能進行顯示。 這種方法意味著在net應用程式中解決一個常見的使用者端-伺服器問題。
在您的Blazor網頁應用中實現JavaScript函式
將此JavaScript程式碼新增到您的_Host.cshtml文件中,以處理在新瀏覽器分頁中顯示PDF。 這是負責客戶端窗口管理的模塊:
<script>
window.openPdfInNewTab = function (pdfData, fileName) {
// Convert base64 to blob
const byteCharacters = atob(pdfData);
const byteNumbers = new Array(byteCharacters.length);
for (let i = 0; i < byteCharacters.length; i++) {
byteNumbers[i] = byteCharacters.charCodeAt(i);
}
const byteArray = new Uint8Array(byteNumbers);
// The type is 'application/pdf', not 'image/png' or 'image/jpg'
const blob = new Blob([byteArray], { type: 'application/pdf' });
// Create URL and open in new tab
const blobUrl = URL.createObjectURL(blob);
const newWindow = window.open(blobUrl, '_blank');
if (newWindow) {
newWindow.document.title = fileName || 'PDF Document';
}
// Clean up
setTimeout(() => URL.revokeObjectURL(blobUrl), 100);
return newWindow !== null;
};
</script>
<script>
window.openPdfInNewTab = function (pdfData, fileName) {
// Convert base64 to blob
const byteCharacters = atob(pdfData);
const byteNumbers = new Array(byteCharacters.length);
for (let i = 0; i < byteCharacters.length; i++) {
byteNumbers[i] = byteCharacters.charCodeAt(i);
}
const byteArray = new Uint8Array(byteNumbers);
// The type is 'application/pdf', not 'image/png' or 'image/jpg'
const blob = new Blob([byteArray], { type: 'application/pdf' });
// Create URL and open in new tab
const blobUrl = URL.createObjectURL(blob);
const newWindow = window.open(blobUrl, '_blank');
if (newWindow) {
newWindow.document.title = fileName || 'PDF Document';
}
// Clean up
setTimeout(() => URL.revokeObjectURL(blobUrl), 100);
return newWindow !== null;
};
</script>
The provided code is JavaScript, not C#. However, I can help you convert it into VB.NET code that would perform a similar function if executed in a VB.NET environment with a web browser control or similar setup. Here's how you might implement similar functionality in VB.NET:
Note: This VB.NET code assumes you are working in a desktop application environment where you can use the `Process.Start` method to open a PDF file with the default PDF viewer. If you are working in a web environment, you would need to adapt this code to fit the web context, possibly using a web server to serve the PDF file to the client.
JavaScript函式window.openPdfInNewTab對於解決從伺服器打開新分頁的挑戰至關重要。 它接受Blazor伺服器和客戶端程式碼中的PDF資料作為Base64字串,將其轉換為二進位Blob物件。
然後使用此blob建立一個臨時URL,最終傳遞給window.open(blobUrl, '_blank'),迫使瀏覽器在新選項卡中打開PDF。
建立Blazor元件
建立一個新的Razor元件,用於生成PDF並在新分頁中開啟。 這是解決方案的主要模板:
@page "/pdf-viewer"
@using IronPDF @inject IJSRuntime JS
<h3>Open PDF in New Tab</h3>
<div class="mb-3">
<label>Enter URL:</label>
</div>
<button class="btn btn-primary" @onclick="GenerateAndOpenPdf"
disabled="@isProcessing">
@if (isProcessing)
{
<span>Generating PDF...</span>
}
else
{
<span>Generate and Open PDF</span>
}
</button>
@if (!string.IsNullOrEmpty(errorMessage))
{
<div class="alert alert-danger mt-3">@errorMessage</div>
}
@code {
private string targetUrl = "https://ironpdf.com";
private bool isProcessing = false;
private string errorMessage = "";
private async Task GenerateAndOpenPdf()
{
isProcessing = true;
errorMessage = "";
try
{
// Configure Chrome PDF renderer. Note the rendering details
var renderer = new ChromePdfRenderer
{
RenderingOptions = new ChromePdfRenderOptions
{
MarginTop = 10,
MarginBottom = 10,
MarginLeft = 10,
MarginRight = 10,
EnableJavaScript = true,
RenderDelay = 500
}
};
// Generate PDF from URL
var pdfDocument = await Task.Run(() =>
renderer.RenderUrlAsPdf(targetUrl));
// Convert to base64
byte[] pdfBytes = pdfDocument.BinaryData;
string base64Pdf = Convert.ToBase64String(pdfBytes);
// Open in new tab via JS interop. We run this call to open the PDF
bool success = await JS.InvokeAsync<bool>("openPdfInNewTab",
base64Pdf, $"Document_{DateTime.Now:yyyyMMdd_HHmmss}.pdf");
if (!success)
{
// Giving the user an understandable error is key
errorMessage = "Pop-up blocked. Please allow pop-ups for this site.";
}
}
catch (Exception ex)
{
errorMessage = $"Error: {ex.Message}";
}
finally
{
isProcessing = false;
}
}
}
@page "/pdf-viewer"
@using IronPDF @inject IJSRuntime JS
<h3>Open PDF in New Tab</h3>
<div class="mb-3">
<label>Enter URL:</label>
</div>
<button class="btn btn-primary" @onclick="GenerateAndOpenPdf"
disabled="@isProcessing">
@if (isProcessing)
{
<span>Generating PDF...</span>
}
else
{
<span>Generate and Open PDF</span>
}
</button>
@if (!string.IsNullOrEmpty(errorMessage))
{
<div class="alert alert-danger mt-3">@errorMessage</div>
}
@code {
private string targetUrl = "https://ironpdf.com";
private bool isProcessing = false;
private string errorMessage = "";
private async Task GenerateAndOpenPdf()
{
isProcessing = true;
errorMessage = "";
try
{
// Configure Chrome PDF renderer. Note the rendering details
var renderer = new ChromePdfRenderer
{
RenderingOptions = new ChromePdfRenderOptions
{
MarginTop = 10,
MarginBottom = 10,
MarginLeft = 10,
MarginRight = 10,
EnableJavaScript = true,
RenderDelay = 500
}
};
// Generate PDF from URL
var pdfDocument = await Task.Run(() =>
renderer.RenderUrlAsPdf(targetUrl));
// Convert to base64
byte[] pdfBytes = pdfDocument.BinaryData;
string base64Pdf = Convert.ToBase64String(pdfBytes);
// Open in new tab via JS interop. We run this call to open the PDF
bool success = await JS.InvokeAsync<bool>("openPdfInNewTab",
base64Pdf, $"Document_{DateTime.Now:yyyyMMdd_HHmmss}.pdf");
if (!success)
{
// Giving the user an understandable error is key
errorMessage = "Pop-up blocked. Please allow pop-ups for this site.";
}
}
catch (Exception ex)
{
errorMessage = $"Error: {ex.Message}";
}
finally
{
isProcessing = false;
}
}
}
Imports IronPDF
Imports Microsoft.JSInterop
@page "/pdf-viewer"
@inject IJSRuntime JS
<h3>Open PDF in New Tab</h3>
<div class="mb-3">
<label>Enter URL:</label>
</div>
<button class="btn btn-primary" @onclick="GenerateAndOpenPdf" disabled="@isProcessing">
@If isProcessing Then
<span>Generating PDF...</span>
Else
<span>Generate and Open PDF</span>
End If
</button>
@If Not String.IsNullOrEmpty(errorMessage) Then
<div class="alert alert-danger mt-3">@errorMessage</div>
End If
@Code
Private targetUrl As String = "https://ironpdf.com"
Private isProcessing As Boolean = False
Private errorMessage As String = ""
Private Async Function GenerateAndOpenPdf() As Task
isProcessing = True
errorMessage = ""
Try
' Configure Chrome PDF renderer. Note the rendering details
Dim renderer As New ChromePdfRenderer With {
.RenderingOptions = New ChromePdfRenderOptions With {
.MarginTop = 10,
.MarginBottom = 10,
.MarginLeft = 10,
.MarginRight = 10,
.EnableJavaScript = True,
.RenderDelay = 500
}
}
' Generate PDF from URL
Dim pdfDocument = Await Task.Run(Function() renderer.RenderUrlAsPdf(targetUrl))
' Convert to base64
Dim pdfBytes As Byte() = pdfDocument.BinaryData
Dim base64Pdf As String = Convert.ToBase64String(pdfBytes)
' Open in new tab via JS interop. We run this call to open the PDF
Dim success As Boolean = Await JS.InvokeAsync(Of Boolean)("openPdfInNewTab", base64Pdf, $"Document_{DateTime.Now:yyyyMMdd_HHmmss}.pdf")
If Not success Then
' Giving the user an understandable error is key
errorMessage = "Pop-up blocked. Please allow pop-ups for this site."
End If
Catch ex As Exception
errorMessage = $"Error: {ex.Message}"
Finally
isProcessing = False
End Try
End Function
End Code
此程式碼塊定義了主要的互動頁面。 Razor標記建立了一個簡單的使用者介面,包含一個URL輸入字段和一個按鈕。 C# @code塊處理邏輯:當點擊按鈕時,它使用ChromePdfRenderer實例從使用者提供的URL生成PDF。
然後它將生成的PDF位元組陣列轉換為@inject IJSRuntime JS調用JavaScript函式,為使用者開擇文件。
UI輸出

在新選項卡中打開的PDF輸出

處理動態HTML內容
若要從動態內容而不是URL生成PDF,請修改您的方法以使用RenderHtmlAsPdf:
private async Task GenerateFromHtml()
{
// Define CSS styles inside the HTML string for structure and appearance.
string htmlContent = $@"
<!DOCTYPE html>
<html>
<head>
<style>
body {{font-family: Arial; padding: 20px;}}
h1 {{color: #2c3e50;}}
</style>
</head>
<body>
<h1>{documentTitle}</h1>
<p>{documentContent}</p>
<div>Generated: {DateTime.Now}</div>
</body>
</html>";
var renderer = new ChromePdfRenderer();
var pdfDocument = renderer.RenderHtmlAsPdf(htmlContent);
byte[] pdfBytes = pdfDocument.BinaryData;
await JS.InvokeVoidAsync("openPdfInNewTab",
Convert.ToBase64String(pdfBytes), "dynamic.pdf");
}
private async Task GenerateFromHtml()
{
// Define CSS styles inside the HTML string for structure and appearance.
string htmlContent = $@"
<!DOCTYPE html>
<html>
<head>
<style>
body {{font-family: Arial; padding: 20px;}}
h1 {{color: #2c3e50;}}
</style>
</head>
<body>
<h1>{documentTitle}</h1>
<p>{documentContent}</p>
<div>Generated: {DateTime.Now}</div>
</body>
</html>";
var renderer = new ChromePdfRenderer();
var pdfDocument = renderer.RenderHtmlAsPdf(htmlContent);
byte[] pdfBytes = pdfDocument.BinaryData;
await JS.InvokeVoidAsync("openPdfInNewTab",
Convert.ToBase64String(pdfBytes), "dynamic.pdf");
}
Imports System
Imports System.Threading.Tasks
Private Async Function GenerateFromHtml() As Task
' Define CSS styles inside the HTML string for structure and appearance.
Dim htmlContent As String = $"
<!DOCTYPE html>
<html>
<head>
<style>
body {{font-family: Arial; padding: 20px;}}
h1 {{color: #2c3e50;}}
</style>
</head>
<body>
<h1>{documentTitle}</h1>
<p>{documentContent}</p>
<div>Generated: {DateTime.Now}</div>
</body>
</html>"
Dim renderer As New ChromePdfRenderer()
Dim pdfDocument = renderer.RenderHtmlAsPdf(htmlContent)
Dim pdfBytes As Byte() = pdfDocument.BinaryData
Await JS.InvokeVoidAsync("openPdfInNewTab", Convert.ToBase64String(pdfBytes), "dynamic.pdf")
End Function
方法GenerateFromHtml演示了IronPDF如何從動態生成的HTML標記而不是現有的URL生成PDF。 它構造了一個包含標題、內容和動態資料的完整HTML字串。 動態內容生成的答案是方法RenderHtmlAsPdf。
更新的Blazor Server UI

在新瀏覽器分頁中打開的PDF

處理常見問題
跨瀏覽器相容性
不同的瀏覽器對blob URL處理方式不同。 在Chrome、Firefox、Edge和Safari上測試您的實現,以確保行為一致。
大型文件
對於大型PDF文件,考慮實施伺服器端快取以提高性能:
services.AddMemoryCache();
// Cache generated PDFs to avoid regeneration
services.AddMemoryCache();
// Cache generated PDFs to avoid regeneration
services.AddMemoryCache()
' Cache generated PDFs to avoid regeneration
導航選項
除了JavaScript互操作,您還可以通過靜態文件中介軟體提供PDF,並使用標準的HTML錨標籤作為另一種導航選項:
<a href="/pdfs/document.pdf" target="_blank">Open PDF</a>
<a href="/pdfs/document.pdf" target="_blank">Open PDF</a>
The provided input is HTML, not C# code. Please provide valid C# code for conversion to VB.NET.
這種方法適用於預生成的PDF,但缺乏JS互操作方法的動態生成功能。
最佳實踐
- 錯誤處理: 始終將PDF生成包在try-catch塊中,並在出現問題時向使用者提供有意義的錯誤消息。
- 性能: 使用async/await模式防止在PDF生成過程中阻塞UI。
- 使用者體驗: 在生成過程中顯示載入指示器,優雅地處理彈出窗口攔截問題。
- DOM 操作: 請記住,伺服器上的C#無法直接操作客戶端的DOM; 這就是為什麼JS互操作至關重要。 您不需要手動設置新窗口的高度或寬度,因為瀏覽器會處理PDF查看器。
- 安全性: 在生成PDF之前驗證並清理使用者輸入
結論
將IronPDF強大的PDF生成能力與Blazor的JavaScript互操作相結合,提供了一個在新的瀏覽器分頁中打開PDF的強大解決方案。 這種方法使開發人員能夠建立動態、專業的PDF文件,無縫整合到使用Microsoft .NET技術構建的現代Blazor應用程式中。
準備好在您的Blazor專案中實現PDF功能嗎? 立即開始您的免費IronPDF試用。 試用版包含完整功能,沒有浮水印,並提供綜合支持以確保您的成功。
常見問題
我如何能使用Blazor在新標籤頁中打開PDF?
您可以使用Blazor生成PDF,然後利用JavaScript互操作在新標籤頁中顯示它來打開PDF。這種方法確保了在查看文件時的流暢使用者體驗。
什麼是Blazor中的JavaScript互操作?
Blazor中的JavaScript互操作允許Blazor應用程式從.NET程式碼調用JavaScript函式,反之亦然。這對於像在新標籤頁中打開PDF這樣的任務非常有用,因為JavaScript可以處理特定瀏覽器的操作。
為什麼我應該使用IronPDF在Blazor中生成PDF?
IronPDF是一個高效的工具,用於在Blazor應用程式中生成PDF。它提供了強大的功能,允許無縫的PDF建立和操作,可以輕鬆地與Blazor的JavaScript互操作結合以增強文件處理。
IronPDF是否與Blazor Server相容?
是的,IronPDF與Blazor Server完全相容。它可以用來生成和管理PDF,然後使用JavaScript互操作在新標籤頁中打開它們。
在Blazor應用程式中在新標籤頁中打開PDF有什麼好處?
在新標籤頁中打開PDF能增強使用者體驗,使使用者能夠在不離開當前頁面的情況下查看文件。這種方法由IronPDF和JavaScript互操作支持,確保更具互動性且不中斷的瀏覽會話。

