# 如何在 .NET 中使用 IronPDF C# 查看 PDF
IronPDF 通過 MAUI 的 `IronPdf.Viewer.Maui` 控制在 .NET 應用程式中顯示 PDF,透過 `RasterizeToImageFiles` 將頁面光柵化為影像以適用於任何 UI 框架,以及通過像 WPF 和 Windows Forms 中的 WebView2 等主機控件進行顯示。 正確的選擇取決於您正在構建的應用程式型別以及您需要多少查看器介面。
在這些路徑中,"查看"有不同的含義。 MAUI 查看器是一個完整的互動組件,帶有工具列。 光柵化路径將每一頁轉成您可以在任何控制項中顯示的影像。 WebView2和預設查看器路径會將檔案交給瀏覽器引擎或使用者安裝的PDF閱讀器。 本文顯示了每一種方式,並誠實地告訴您它們能夠和不能夠為您提供什麼。
迅速入門:使用 IronPDF 在 MAUI 中查看 PDF
新增 `IronPdf.Viewer.Maui` NuGet 套件,然後在 `MauiProgram.cs` 中調用 `ConfigureIronPdfView()`,接著將 PDF 綁定到 `IronPdfView`。 下面的單行程式碼將文件載入到查看器控制中。
```cs
:title=Load a PDF into the MAUI viewer in one line!
new IronPdf.Viewer.Maui.IronPdfView { Source = IronPdf.Viewer.Maui.IronPdfViewSource.FromFile("document.pdf") };
```
首先使用 `Install-Package IronPdf.Viewer.Maui` 安裝套件,然後在 `ConfigureIronPdfView` 中新增您的 IronPDF 授權金鑰以移除試用橫幅。 [MAUI 查看器教程](/tutorials/pdf-viewing/)會介紹完整的項目設置過程。
<div class="hsg-featured-snippet">
<h3>最小工作流程 (5步)</h3>
<ol>
<li><a class="js-modal-open" data-modal-id="trial-license-after-download" href="https://www.nuget.org/packages/IronPdf/">從 NuGet 安裝 IronPDF 以進行.NET PDF 渲染</a></li>
<li>選擇觀看路徑:MAUI 查看器,光柵化成影像,WebView2 或預設系統查看器</li>
<li>在 ASP.NET 中嵌入 PDF 使用 HTML <code>iframe</code></li>
<li>將 PDF 頁面渲染為影像以供 WPF、WinForms 或 Blazor 顯示</li>
<li>使用 <code>System.Diagnostics.Process.Start</code> 在使用者安裝的閱讀器中打開 PDF</li>
</ol>
</div>
<br class="clear" />
## 如何在 ASP.NET 和 MVC 中查看 PDF?
從控制器動作提供 PDF,並使用 HTML `iframe` 嵌入它。 瀏覽器內建的 PDF 查看器處理渲染,因此文件會內嵌顯示,而頁面佈局保持不變。 當即時生成 PDF 時,IronPDF 的 [HTML 到 PDF 轉換](/how-to/html-string-to-pdf/) 產生的文件會由動作返回。
```csharp
// Controller action to serve PDF
public ActionResult ViewPdf()
{
var pdfPath = Server.MapPath("~/Content/sample.pdf");
return File(pdfPath, "application/pdf");
}
// In your Razor view
<iframe src="@Url.Action("ViewPdf")" width="100%" height="600px"></iframe>
```
如果您需要文字選擇、縮放以及您控制的頁面導航而非瀏覽器預設,則將 PDF 頁面渲染為影像(如下所示)並顯示它們,或連接您選擇的 JavaScript 查看器。
<hr class="separator" />
## 如何在 WPF、WinForms 或 Blazor 中顯示 PDF 頁面為影像?
調用 `RasterizeToImageFiles` 將每個 PDF 頁面轉換為 PNG,然後在任何控件中顯示這些影像:WPF `Image`,WinForms `PictureBox` 或在 Blazor 組件中的 `<img>`。 這是 IronPDF 原生的查看路徑。 它在每個夾層框架和每個 IronPDF 支持的作業系統上都能正常運作,因為它產生的只是普通影像文件而不依賴於主機瀏覽器控制。
### 輸入
<iframe loading="lazy" src="/static-assets/pdf/how-to/net-pdf-viewer/sample-report.pdf" width="100%" height="500px"></iframe>
```csharp
using IronPdf;
// Load the PDF you want to display.
PdfDocument pdf = PdfDocument.FromFile("sample-report.pdf");
// Render every page to a PNG. The asterisk in the path is replaced with the page number,
// producing viewer-page-1.png, viewer-page-2.png, and so on. The last argument (100) is the DPI.
pdf.RasterizeToImageFiles("viewer-page-*.png", IronPdf.Imaging.ImageType.Png, 100);
// To show a page inside a GUI control without writing to disk, get in-memory bitmaps instead.
// ToBitmap returns one AnyBitmap per page; bind bitmaps[0] to a WPF Image or a WinForms PictureBox.
var bitmaps = pdf.ToBitmap();
bitmaps[0].SaveAs("viewer-firstpage.png");
```
### 輸出
<img src="/static-assets/pdf/how-to/net-pdf-viewer/rasterized-page-1.png" alt="將範例報表 PDF 的第一頁點陣化為 PNG 影像,以顯示於 .NET UI 控制項中" width="100%" class="img-responsive add-shadow" />
對於記憶體選項,`ToBitmap` 實現每頁一張影像,可以不經磁碟的直接綁定到控制項。 調整 DPI 參數可以在文件大小與清晰度間取捨,與您製作文件時控制 IronPDF [渲染選項](/how-to/rendering-options/) 一樣。
<hr class="separator" />
## 如何在 WPF 應用程式中查看 PDF?
將 PDF 設置在 WebView2 控件中,使用來自 Microsoft Edge 的 Chromium 引擎,並附帶自己的 PDF 查看器(包括工具列、縮放和列印功能)。 將文件存到磁碟,再導航控制項到檔案 URI。 WebView2 目前替代舊的 `WebBrowser` 控件,依賴於被棄用的 Internet Explorer 引擎。
```csharp
// WPF: display a PDF using the WebView2 control (Microsoft Edge / Chromium).
// Install the NuGet package Microsoft.Web.WebView2 and add a <wv2:WebView2 x:Name="pdfWebView" />
// element to your XAML (xmlns:wv2="clr-namespace:Microsoft.Web.WebView2.Wpf;assembly=Microsoft.Web.WebView2.Wpf").
// WebView2 renders PDFs with the same built-in viewer as the Edge browser (toolbar, zoom, print).
using System;
using System.IO;
// Save the IronPDF-generated document to disk first, then point WebView2 at it.
var pdf = new IronPdf.ChromePdfRenderer().RenderHtmlAsPdf("<h1>Hello IronPDF</h1>");
string pdfPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "document.pdf");
pdf.SaveAs(pdfPath);
// pdfWebView is the WebView2 control declared in your XAML.
// EnsureCoreWebView2Async must complete before navigating.
await pdfWebView.EnsureCoreWebView2Async();
pdfWebView.CoreWebView2.Navigate(new Uri(pdfPath).AbsoluteUri);
// Legacy alternative: the older System.Windows.Controls.WebBrowser control still works on
// Windows machines that have a PDF handler installed, but it relies on the deprecated Internet
// Explorer engine and is not recommended for new applications. Prefer WebView2 above.
```
[[w:(WebView2 在目標機器上要求安裝 Microsoft Edge WebView2 Runtime。在當前 Windows 11 構建中預裝; 舊系統可使用永恆更新安裝程式附帶安裝程式。)]}
)]]
<hr class="separator" />
## 如何在 Windows Forms 中查看 PDF?
將 WebView2 控件拖放到表單上並指向已保存的 PDF,與在 WPF 中正如所示。 控件異步初始化,因而在調用 `Navigate` 前等待 `EnsureCoreWebView2Async`。 這給 WinForms 應用程式相同的基於 Chromium 的查看器,不需捆綁第三方組件。
```csharp
// Windows Forms: display a PDF using the WebView2 control (Microsoft Edge / Chromium).
// Install the NuGet package Microsoft.Web.WebView2, then drag a WebView2 control onto your form
// (or add it in code) and name it pdfWebView.
using System;
using System.IO;
// Generate or load the PDF with IronPDF, then save it so WebView2 can open the file.
var pdf = new IronPdf.ChromePdfRenderer().RenderHtmlAsPdf("<h1>Hello IronPDF</h1>");
string pdfPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "document.pdf");
pdf.SaveAs(pdfPath);
// pdfWebView is the WebView2 control on your form.
// Initialize the runtime, then navigate to the local file URI.
await pdfWebView.EnsureCoreWebView2Async();
pdfWebView.CoreWebView2.Navigate(new Uri(pdfPath).AbsoluteUri);
// Legacy alternative: the System.Windows.Forms.WebBrowser control can host a PDF when a system
// PDF handler is registered, but it uses the deprecated Internet Explorer engine. Use WebView2
// for new projects so the viewer works consistently across modern Windows installs.
```
如果您不想在主機上控制任何瀏覽器控制,則上面部分的 基於影像的方法 可以直接用於 `PictureBox` 並完全避免約束於 WebView2 運行時依賴。
<hr class="separator" />
## 如何在預設系統的 PDF 查看器中查看 PDF?
將文件路徑傳至 `System.Diagnostics.Process.Start`,以打開使用者設定為預設的任何閱讀器中的 PDF,如瀏覽器或 Adobe Acrobat。 這將渲染交給外部應用程式而不是嵌入它,適合於僅需顯示完成檔案的工具和批處理工具。
```csharp
using IronPdf;
// Render any HTML fragment or document to HTML
ChromePdfRenderer renderer = new ChromePdfRenderer();
PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>Hello IronPdf</h1>");
var outputPath = "ChromePdfRenderer.pdf";
// Export PDF document
pdf.SaveAs(outputPath);
// This neat trick opens our PDF file so we can see the result in our default PDF viewer
System.Diagnostics.Process.Start(outputPath);
```
在生產中,對調用進行包裝以確保不存在 PDF 處理程式不會使應用崩潰:
```csharp
try
{
var psi = new System.Diagnostics.ProcessStartInfo
{
FileName = outputPath,
UseShellExecute = true
};
System.Diagnostics.Process.Start(psi);
}
catch (Exception ex)
{
// Handle the case where no PDF viewer is installed
MessageBox.Show($"Unable to open PDF: {ex.Message}");
}
```
## 總結
這裡的每一條查看路徑都在交互能力和可攜性之間做出取捨:MAUI 查看器提供完整的工具列,光柵化為影像可以在任何平台上的任何 UI 中使用,WebView2 重用 Edge 引擎及 `Process.Start` 順從使用者的閱讀器。 選擇與您的應用匹配的,而不是強求一種解答。
由於大部分查看開始於您生成的文件,所以當您需要交互工具列時,將這些技術與完整的 [MAUI 查看器教程](/tutorials/pdf-viewing/) 配合使用。
使用 System.Diagnostics.Process.Start 在使用者安裝的閱讀器中打開 PDF
如何在 ASP.NET 和 MVC 中查看 PDF?
從控制器動作提供 PDF,並使用 HTML iframe 嵌入它。 瀏覽器內建的 PDF 查看器處理渲染,因此文件會內嵌顯示,而頁面佈局保持不變。 當即時生成 PDF 時,IronPDF 的 HTML 到 PDF 轉換 產生的文件會由動作返回。
// Controller action to serve PDFpublic ActionResultViewPdf(){ var pdfPath = Server.MapPath("~/Content/sample.pdf"); returnFile(pdfPath, "application/pdf");}// In your Razor view<iframe src="@Url.Action("ViewPdf")" width="100%" height="600px"></iframe>
// Controller action to serve PDF
public ActionResult ViewPdf()
{
var pdfPath = Server.MapPath("~/Content/sample.pdf");
return File(pdfPath, "application/pdf");
}
// In your Razor view
<iframe src="@Url.Action("ViewPdf")" width="100%" height="600px"></iframe>
ImportsSystem.Web.Mvc' Controller action to serve PDFPublic Function ViewPdf() AsActionResult Dim pdfPath = Server.MapPath("~/Content/sample.pdf") ReturnFile(pdfPath, "application/pdf")End Function' In your Razor view<iframe src="@Url.Action("ViewPdf")" width="100%" height="600px"></iframe>
Imports System.Web.Mvc
' Controller action to serve PDF
Public Function ViewPdf() As ActionResult
Dim pdfPath = Server.MapPath("~/Content/sample.pdf")
Return File(pdfPath, "application/pdf")
End Function
' In your Razor view
<iframe src="@Url.Action("ViewPdf")" width="100%" height="600px"></iframe>
如果您需要文字選擇、縮放以及您控制的頁面導航而非瀏覽器預設,則將 PDF 頁面渲染為影像(如下所示)並顯示它們,或連接您選擇的 JavaScript 查看器。
using IronPdf;// Load the PDF you want to display.PdfDocument pdf = PdfDocument.FromFile("sample-report.pdf");// Render every page to a PNG. The asterisk in the path is replaced with the page number,// producing viewer-page-1.png, viewer-page-2.png, and so on. The last argument (100) is the DPI.pdf.RasterizeToImageFiles("viewer-page-*.png", IronPdf.Imaging.ImageType.Png, 100);// To show a page inside a GUI control without writing to disk, get in-memory bitmaps instead.// ToBitmap returns one AnyBitmap per page; bind bitmaps[0] to a WPF Image or a WinForms PictureBox.var bitmaps = pdf.ToBitmap();bitmaps[0].SaveAs("viewer-firstpage.png");
using IronPdf;
// Load the PDF you want to display.
PdfDocument pdf = PdfDocument.FromFile("sample-report.pdf");
// Render every page to a PNG. The asterisk in the path is replaced with the page number,
// producing viewer-page-1.png, viewer-page-2.png, and so on. The last argument (100) is the DPI.
pdf.RasterizeToImageFiles("viewer-page-*.png", IronPdf.Imaging.ImageType.Png, 100);
// To show a page inside a GUI control without writing to disk, get in-memory bitmaps instead.
// ToBitmap returns one AnyBitmap per page; bind bitmaps[0] to a WPF Image or a WinForms PictureBox.
var bitmaps = pdf.ToBitmap();
bitmaps[0].SaveAs("viewer-firstpage.png");
將 PDF 設置在 WebView2 控件中,使用來自 Microsoft Edge 的 Chromium 引擎,並附帶自己的 PDF 查看器(包括工具列、縮放和列印功能)。 將文件存到磁碟,再導航控制項到檔案 URI。 WebView2 目前替代舊的 WebBrowser 控件,依賴於被棄用的 Internet Explorer 引擎。
// WPF: display a PDF using the WebView2 control (Microsoft Edge / Chromium).// Install the NuGet package Microsoft.Web.WebView2 and add a <wv2:WebView2 x:Name="pdfWebView" />// element to your XAML (xmlns:wv2="clr-namespace:Microsoft.Web.WebView2.Wpf;assembly=Microsoft.Web.WebView2.Wpf").// WebView2 renders PDFs with the same built-in viewer as the Edge browser (toolbar, zoom, print).using System;using System.IO;// Save the IronPDF-generated document to disk first, then point WebView2 at it.var pdf = new IronPdf.ChromePdfRenderer().RenderHtmlAsPdf("<h1>Hello IronPDF</h1>");string pdfPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "document.pdf");pdf.SaveAs(pdfPath);// pdfWebView is the WebView2 control declared in your XAML.// EnsureCoreWebView2Async must complete before navigating.await pdfWebView.EnsureCoreWebView2Async();pdfWebView.CoreWebView2.Navigate(new Uri(pdfPath).AbsoluteUri);// Legacy alternative: the older System.Windows.Controls.WebBrowser control still works on// Windows machines that have a PDF handler installed, but it relies on the deprecated Internet// Explorer engine and is not recommended for new applications. Prefer WebView2 above.
// WPF: display a PDF using the WebView2 control (Microsoft Edge / Chromium).
// Install the NuGet package Microsoft.Web.WebView2 and add a <wv2:WebView2 x:Name="pdfWebView" />
// element to your XAML (xmlns:wv2="clr-namespace:Microsoft.Web.WebView2.Wpf;assembly=Microsoft.Web.WebView2.Wpf").
// WebView2 renders PDFs with the same built-in viewer as the Edge browser (toolbar, zoom, print).
using System;
using System.IO;
// Save the IronPDF-generated document to disk first, then point WebView2 at it.
var pdf = new IronPdf.ChromePdfRenderer().RenderHtmlAsPdf("<h1>Hello IronPDF</h1>");
string pdfPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "document.pdf");
pdf.SaveAs(pdfPath);
// pdfWebView is the WebView2 control declared in your XAML.
// EnsureCoreWebView2Async must complete before navigating.
await pdfWebView.EnsureCoreWebView2Async();
pdfWebView.CoreWebView2.Navigate(new Uri(pdfPath).AbsoluteUri);
// Legacy alternative: the older System.Windows.Controls.WebBrowser control still works on
// Windows machines that have a PDF handler installed, but it relies on the deprecated Internet
// Explorer engine and is not recommended for new applications. Prefer WebView2 above.
C#
警告: WebView2 在目標機器上要求安裝 Microsoft Edge WebView2 Runtime。在當前 Windows 11 構建中預裝; 舊系統可使用永恆更新安裝程式附帶安裝程式。)]}
// Windows Forms: display a PDF using the WebView2 control (Microsoft Edge / Chromium).// Install the NuGet package Microsoft.Web.WebView2, then drag a WebView2 control onto your form// (or add it in code) and name it pdfWebView.using System;using System.IO;// Generate or load the PDF with IronPDF, then save it so WebView2 can open the file.var pdf = new IronPdf.ChromePdfRenderer().RenderHtmlAsPdf("<h1>Hello IronPDF</h1>");string pdfPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "document.pdf");pdf.SaveAs(pdfPath);// pdfWebView is the WebView2 control on your form.// Initialize the runtime, then navigate to the local file URI.await pdfWebView.EnsureCoreWebView2Async();pdfWebView.CoreWebView2.Navigate(new Uri(pdfPath).AbsoluteUri);// Legacy alternative: the System.Windows.Forms.WebBrowser control can host a PDF when a system// PDF handler is registered, but it uses the deprecated Internet Explorer engine. Use WebView2// for new projects so the viewer works consistently across modern Windows installs.
// Windows Forms: display a PDF using the WebView2 control (Microsoft Edge / Chromium).
// Install the NuGet package Microsoft.Web.WebView2, then drag a WebView2 control onto your form
// (or add it in code) and name it pdfWebView.
using System;
using System.IO;
// Generate or load the PDF with IronPDF, then save it so WebView2 can open the file.
var pdf = new IronPdf.ChromePdfRenderer().RenderHtmlAsPdf("<h1>Hello IronPDF</h1>");
string pdfPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "document.pdf");
pdf.SaveAs(pdfPath);
// pdfWebView is the WebView2 control on your form.
// Initialize the runtime, then navigate to the local file URI.
await pdfWebView.EnsureCoreWebView2Async();
pdfWebView.CoreWebView2.Navigate(new Uri(pdfPath).AbsoluteUri);
// Legacy alternative: the System.Windows.Forms.WebBrowser control can host a PDF when a system
// PDF handler is registered, but it uses the deprecated Internet Explorer engine. Use WebView2
// for new projects so the viewer works consistently across modern Windows installs.
using IronPdf;// Render any HTML fragment or document to HTMLChromePdfRenderer renderer = new ChromePdfRenderer();PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>Hello IronPdf</h1>");var outputPath = "ChromePdfRenderer.pdf";// Export PDF documentpdf.SaveAs(outputPath);// This neat trick opens our PDF file so we can see the result in our default PDF viewerSystem.Diagnostics.Process.Start(outputPath);
using IronPdf;
// Render any HTML fragment or document to HTML
ChromePdfRenderer renderer = new ChromePdfRenderer();
PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>Hello IronPdf</h1>");
var outputPath = "ChromePdfRenderer.pdf";
// Export PDF document
pdf.SaveAs(outputPath);
// This neat trick opens our PDF file so we can see the result in our default PDF viewer
System.Diagnostics.Process.Start(outputPath);
ImportsIronPdf' Render any HTML fragment or document to HTMLPrivate renderer As New ChromePdfRenderer()Private pdf AsPdfDocument = renderer.RenderHtmlAsPdf("<h1>Hello IronPdf</h1>")Private outputPath = "ChromePdfRenderer.pdf"' Export PDF documentpdf.SaveAs(outputPath)' This neat trick opens our PDF file so we can see the result in our default PDF viewerSystem.Diagnostics.Process.Start(outputPath)
Imports IronPdf
' Render any HTML fragment or document to HTML
Private renderer As New ChromePdfRenderer()
Private pdf As PdfDocument = renderer.RenderHtmlAsPdf("<h1>Hello IronPdf</h1>")
Private outputPath = "ChromePdfRenderer.pdf"
' Export PDF document
pdf.SaveAs(outputPath)
' This neat trick opens our PDF file so we can see the result in our default PDF viewer
System.Diagnostics.Process.Start(outputPath)
在生產中,對調用進行包裝以確保不存在 PDF 處理程式不會使應用崩潰:
try{ var psi = new System.Diagnostics.ProcessStartInfo {FileName = outputPath,UseShellExecute = true };System.Diagnostics.Process.Start(psi);}catch (Exception ex){ // Handle the case where no PDF viewer is installedMessageBox.Show($"Unable to open PDF: {ex.Message}");}
try
{
var psi = new System.Diagnostics.ProcessStartInfo
{
FileName = outputPath,
UseShellExecute = true
};
System.Diagnostics.Process.Start(psi);
}
catch (Exception ex)
{
// Handle the case where no PDF viewer is installed
MessageBox.Show($"Unable to open PDF: {ex.Message}");
}
ImportsSystem.DiagnosticsImportsSystem.Windows.FormsTry Dim psi As New ProcessStartInfoWith { .FileName = outputPath, .UseShellExecute = True }Process.Start(psi)Catch ex AsException ' Handle the case where no PDF viewer is installedMessageBox.Show($"Unable to open PDF: {ex.Message}")EndTry
Imports System.Diagnostics
Imports System.Windows.Forms
Try
Dim psi As New ProcessStartInfo With {
.FileName = outputPath,
.UseShellExecute = True
}
Process.Start(psi)
Catch ex As Exception
' Handle the case where no PDF viewer is installed
MessageBox.Show($"Unable to open PDF: {ex.Message}")
End Try
How can I open a PDF in the default system viewer using IronPDF?
Use System.Diagnostics.Process.Start with the PDF file path to open it in the user's default PDF reader, such as a browser or Adobe Acrobat.
Is it possible to display PDFs in Blazor applications with IronPDF?
Yes, you can convert each PDF page to an image using IronPDF's RasterizeToImageFiles, and display those images using an img tag in a Blazor component.
What should I do if the default PDF viewer is not installed on the user's system?
Wrap the System.Diagnostics.Process.Start call in a try-catch block to handle cases where a PDF viewer is missing, ensuring your application does not crash.
How can IronPDF's MAUI viewer enhance my application's PDF viewing experience?
The MAUI viewer provides a full interactive component with a toolbar, allowing users to interact with the PDF directly within your app.
Can I use IronPDF to integrate PDF viewing capabilities without depending on browser controls?
Yes, by rasterizing PDF pages to images, you can integrate viewing capabilities in any UI framework without relying on browser-based controls.