C#在默認查看器中使用IronPDF (.NET 10)打開PDF
在 .NET 應用程式開發中,使用預設檢視器開啟 PDF 檔案是一項常見任務。 使用IronPDF以程式設計方式產生 PDF 檔案後,通常需要立即在使用者選擇的預設應用程式(例如 Adobe Acrobat 或 Microsoft Edge)中向使用者顯示這些檔案。 本指南將引導您完成使用IronPDF產生 PDF 檔案並使用 System.Diagnostics.Process.Start 在 Windows 中自動開啟它們的步驟。
IronPDF 強大的HTML 到 PDF 轉換功能與簡單的 Process 啟動方法相結合,為在使用者電腦上配置的預設應用程式中建立和顯示專業 PDF 檔案建立了一個實用的工作流程。
如何在 .NET 專案中安裝 IronPDF?
在產生或開啟任何 PDF 檔案之前,您的專案中需要安裝 IronPDF。 可以使用 NuGet 套件管理器控制台或 .NET 命令列介面:
Install-Package IronPdf
dotnet add package IronPdf
Install-Package IronPdf
dotnet add package IronPdf
安裝完成後,請新增您的許可證金鑰或開始免費試用以啟用全部功能。 IronPDF 文件詳細介紹了所有設定選項,包括透過 NuGet 安裝。
安裝完成後,您就可以使用IronPDF 的全部功能,包括 HTML 轉 PDF、URL 渲染、PDF 合併、浮水印、數位簽章等等。
如何產生和開啟PDF文件?
最直接的方法包括三個步驟:
- 使用 IronPDF 建立 PDF 文件。
- 將檔案儲存到目錄。
- 使用
Process.Start在預設應用程式中開啟 PDF。
以下是一個完整的可運行範例,您可以在 Visual Studio 中使用新的控制台應用程式專案進行嘗試:
using IronPdf;
using System.Diagnostics;
// Create a new PDF renderer
var renderer = new ChromePdfRenderer();
// Generate PDF from HTML content
var pdf = renderer.RenderHtmlAsPdf(@"
<html>
<body>
<h1>Invoice #12345</h1>
<p>Generated on: " + DateTime.Now.ToString("yyyy-MM-dd") + @"</p>
<table>
<tr><td>Product</td><td>Price</td></tr>
<tr><td>IronPDF License</td><td>$299</td></tr>
</table>
</body>
</html>");
// Save the PDF to a file
string outputPath = "invoice.pdf";
pdf.SaveAs(outputPath);
// Open the PDF in the default viewer
Process.Start(new ProcessStartInfo
{
FileName = outputPath,
UseShellExecute = true
});
using IronPdf;
using System.Diagnostics;
// Create a new PDF renderer
var renderer = new ChromePdfRenderer();
// Generate PDF from HTML content
var pdf = renderer.RenderHtmlAsPdf(@"
<html>
<body>
<h1>Invoice #12345</h1>
<p>Generated on: " + DateTime.Now.ToString("yyyy-MM-dd") + @"</p>
<table>
<tr><td>Product</td><td>Price</td></tr>
<tr><td>IronPDF License</td><td>$299</td></tr>
</table>
</body>
</html>");
// Save the PDF to a file
string outputPath = "invoice.pdf";
pdf.SaveAs(outputPath);
// Open the PDF in the default viewer
Process.Start(new ProcessStartInfo
{
FileName = outputPath,
UseShellExecute = true
});
Imports IronPdf
Imports System.Diagnostics
' Create a new PDF renderer
Dim renderer As New ChromePdfRenderer()
' Generate PDF from HTML content
Dim pdf = renderer.RenderHtmlAsPdf("
<html>
<body>
<h1>Invoice #12345</h1>
<p>Generated on: " & DateTime.Now.ToString("yyyy-MM-dd") & "</p>
<table>
<tr><td>Product</td><td>Price</td></tr>
<tr><td>IronPDF License</td><td>$299</td></tr>
</table>
</body>
</html>")
' Save the PDF to a file
Dim outputPath As String = "invoice.pdf"
pdf.SaveAs(outputPath)
' Open the PDF in the default viewer
Process.Start(New ProcessStartInfo With {
.FileName = outputPath,
.UseShellExecute = True
})
這段程式碼首先建立了 ChromePdfRenderer 實例,這是 IronPDF 的主要類,用於將 HTML 轉換為 PDF。 RenderHtmlAsPdf 方法將 HTML 字串轉換為 PDF 文件物件。 有關此方法的更多信息,請參閱IronPDF 的 HTML 轉 PDF 指南。
使用 SaveAs 儲存 PDF 後,程式碼使用 Process.Start 和 ProcessStartInfo 在預設 PDF 檢視器中開啟該檔案。 這裡的關鍵設定是 UseShellExecute = true,它告訴 Windows 使用其預設應用程式開啟 PDF 檔案。
輸出
如下圖所示,IronPDF 成功產生 PDF 文件,並使用系統上配置的預設檢視器(在本例中為 Opera GX)顯示該文件。
為什麼需要頂級語句?
使用 .NET 10 和現代 C# 版本,頂級語句不再需要 Program 類別包裝器。 程式碼直接從文件頂部開始運行,使得範例更短更易於理解。 本指南中的所有範例均採用此模式。
為什麼在開啟 PDF 文件時 UseShellExecute 很重要?
在 .NET Core 和現代 .NET 版本(.NET 5 到 .NET 10)中,UseShellExecute 參數預設為 false。 如果沒有明確地將其設定為 true,您的應用程式在嘗試啟動 PDF 檔案時將拋出錯誤。
using IronPdf;
using System.Diagnostics;
using System.IO;
// Generate a report with IronPDF
var renderer = new ChromePdfRenderer();
renderer.RenderingOptions.MarginTop = 50;
renderer.RenderingOptions.MarginBottom = 50;
var pdf = renderer.RenderUrlAsPdf("https://en.wikipedia.org/wiki/Main_Page");
// Save to temp directory for immediate viewing
string tempPath = Path.Combine(Path.GetTempPath(), $"URL_{Guid.NewGuid()}.pdf");
pdf.SaveAs(tempPath);
// IMPORTANT: Set UseShellExecute = true for .NET Core/5+
var startInfo = new ProcessStartInfo
{
FileName = tempPath,
UseShellExecute = true // Required in .NET Core/5+ to open PDF in default viewer
};
Process.Start(startInfo);
using IronPdf;
using System.Diagnostics;
using System.IO;
// Generate a report with IronPDF
var renderer = new ChromePdfRenderer();
renderer.RenderingOptions.MarginTop = 50;
renderer.RenderingOptions.MarginBottom = 50;
var pdf = renderer.RenderUrlAsPdf("https://en.wikipedia.org/wiki/Main_Page");
// Save to temp directory for immediate viewing
string tempPath = Path.Combine(Path.GetTempPath(), $"URL_{Guid.NewGuid()}.pdf");
pdf.SaveAs(tempPath);
// IMPORTANT: Set UseShellExecute = true for .NET Core/5+
var startInfo = new ProcessStartInfo
{
FileName = tempPath,
UseShellExecute = true // Required in .NET Core/5+ to open PDF in default viewer
};
Process.Start(startInfo);
Imports IronPdf
Imports System.Diagnostics
Imports System.IO
' Generate a report with IronPDF
Dim renderer As New ChromePdfRenderer()
renderer.RenderingOptions.MarginTop = 50
renderer.RenderingOptions.MarginBottom = 50
Dim pdf = renderer.RenderUrlAsPdf("https://en.wikipedia.org/wiki/Main_Page")
' Save to temp directory for immediate viewing
Dim tempPath As String = Path.Combine(Path.GetTempPath(), $"URL_{Guid.NewGuid()}.pdf")
pdf.SaveAs(tempPath)
' IMPORTANT: Set UseShellExecute = true for .NET Core/5+
Dim startInfo As New ProcessStartInfo With {
.FileName = tempPath,
.UseShellExecute = True ' Required in .NET Core/5+ to open PDF in default viewer
}
Process.Start(startInfo)
UseShellExecute 屬性決定是否使用作業系統 shell 來啟動進程。 當設定為 true 時,Windows 會使用檔案關聯註冊表來決定哪個預設 PDF 讀取器應該開啟該檔案。在現代 .NET 版本中,如果沒有此設置,您將遇到運行時錯誤,提示無法開啟該檔案。
使用具有唯一檔案名稱的臨時目錄(透過 Guid.NewGuid())可以防止在快速連續產生多個 PDF 時發生檔案衝突。 作業系統會定期自動清理預設的臨時資料夾。
輸出
如何正確處理檔案路徑?
包含空格和特殊字元的檔案路徑需要謹慎處理。 缺少目錄或路徑格式錯誤會在到達 Process.Start 之前靜默失敗或拋出異常。 以下是一種包含目錄建立和檔案存在性檢查的方法:
using IronPdf;
using System.Diagnostics;
using System.IO;
// Generate PDF from HTML file
var renderer = new ChromePdfRenderer();
var htmlContent = File.ReadAllText("template.html");
var pdf = renderer.RenderHtmlAsPdf(htmlContent);
// Create output directory if it doesn't exist
string outputDir = @"C:\PDF Reports\Monthly";
Directory.CreateDirectory(outputDir);
// Build file path with timestamp
string fileName = $"Report_{DateTime.Now:yyyyMMdd_HHmmss}.pdf";
string fullPath = Path.Combine(outputDir, fileName);
// Save the PDF
pdf.SaveAs(fullPath);
// Verify file exists before opening in default PDF viewer
if (File.Exists(fullPath))
{
Process.Start(new ProcessStartInfo
{
FileName = fullPath,
UseShellExecute = true
});
}
else
{
Console.WriteLine($"Error: PDF file not found at {fullPath}");
}
using IronPdf;
using System.Diagnostics;
using System.IO;
// Generate PDF from HTML file
var renderer = new ChromePdfRenderer();
var htmlContent = File.ReadAllText("template.html");
var pdf = renderer.RenderHtmlAsPdf(htmlContent);
// Create output directory if it doesn't exist
string outputDir = @"C:\PDF Reports\Monthly";
Directory.CreateDirectory(outputDir);
// Build file path with timestamp
string fileName = $"Report_{DateTime.Now:yyyyMMdd_HHmmss}.pdf";
string fullPath = Path.Combine(outputDir, fileName);
// Save the PDF
pdf.SaveAs(fullPath);
// Verify file exists before opening in default PDF viewer
if (File.Exists(fullPath))
{
Process.Start(new ProcessStartInfo
{
FileName = fullPath,
UseShellExecute = true
});
}
else
{
Console.WriteLine($"Error: PDF file not found at {fullPath}");
}
Imports IronPdf
Imports System.Diagnostics
Imports System.IO
' Generate PDF from HTML file
Dim renderer As New ChromePdfRenderer()
Dim htmlContent As String = File.ReadAllText("template.html")
Dim pdf = renderer.RenderHtmlAsPdf(htmlContent)
' Create output directory if it doesn't exist
Dim outputDir As String = "C:\PDF Reports\Monthly"
Directory.CreateDirectory(outputDir)
' Build file path with timestamp
Dim fileName As String = $"Report_{DateTime.Now:yyyyMMdd_HHmmss}.pdf"
Dim fullPath As String = Path.Combine(outputDir, fileName)
' Save the PDF
pdf.SaveAs(fullPath)
' Verify file exists before opening in default PDF viewer
If File.Exists(fullPath) Then
Process.Start(New ProcessStartInfo With {
.FileName = fullPath,
.UseShellExecute = True
})
Else
Console.WriteLine($"Error: PDF file not found at {fullPath}")
End If
這段程式碼示範了幾個最佳實踐:使用 Path.Combine 正確建立檔案路徑,而無需考慮作業系統;使用 Directory.CreateDirectory 根據需要建立目錄;以及在嘗試使用預設檢視器開啟 PDF 之前驗證檔案是否存在。
檔案名稱中的時間戳確保了唯一性,並清楚地記錄了每個 PDF 檔案的生成時間。 對於合併或分割 PDF 、新增浮水印、數位簽章以及頁首和頁尾等進階 PDF 操作選項,請瀏覽 IronPDF 的操作指南。
路徑中若包含空格呢?
Path.Combine 能正確處理空格,因為它將路徑建構成字串,而不是依賴 shell 擴充。 ProcessStartInfo 類別也能正確處理引號的路徑,當 UseShellExecute = true 時。 如果直接將路徑傳遞給 shell 指令,請務必用雙引號將其括起來。 使用 Process.Start,FileName 屬性不需要手動加引號。
如何應用生產就緒的最佳實務?
對於生產應用,請考慮採用更完善的工作流程,該流程能夠處理 PDF 生命週期,並提供錯誤處理、可配置的渲染選項和可預測的輸出目錄:
using IronPdf;
using IronPdf.Rendering;
using System.Diagnostics;
using System.IO;
static void GenerateAndDisplayPdf(string htmlContent, string documentName)
{
try
{
// Configure IronPDF renderer with production settings
var renderer = new ChromePdfRenderer
{
RenderingOptions = new ChromePdfRenderOptions
{
PaperSize = PdfPaperSize.A4,
PrintHtmlBackgrounds = true,
CreatePdfFormsFromHtml = true
}
};
// Generate the PDF
var pdf = renderer.RenderHtmlAsPdf(htmlContent);
// Use the user's Documents folder for better accessibility
string documentsPath = Environment.GetFolderPath(
Environment.SpecialFolder.MyDocuments);
string pdfFolder = Path.Combine(documentsPath, "Generated PDFs");
Directory.CreateDirectory(pdfFolder);
string outputPath = Path.Combine(pdfFolder, $"{documentName}.pdf");
pdf.SaveAs(outputPath);
// Open PDF in default viewer without waiting for it to close
Process.Start(new ProcessStartInfo
{
FileName = outputPath,
UseShellExecute = true // Essential for opening PDF in default application
});
Console.WriteLine($"PDF opened: {outputPath}");
}
catch (Exception ex)
{
Console.WriteLine($"Error generating or opening PDF: {ex.Message}");
}
}
using IronPdf;
using IronPdf.Rendering;
using System.Diagnostics;
using System.IO;
static void GenerateAndDisplayPdf(string htmlContent, string documentName)
{
try
{
// Configure IronPDF renderer with production settings
var renderer = new ChromePdfRenderer
{
RenderingOptions = new ChromePdfRenderOptions
{
PaperSize = PdfPaperSize.A4,
PrintHtmlBackgrounds = true,
CreatePdfFormsFromHtml = true
}
};
// Generate the PDF
var pdf = renderer.RenderHtmlAsPdf(htmlContent);
// Use the user's Documents folder for better accessibility
string documentsPath = Environment.GetFolderPath(
Environment.SpecialFolder.MyDocuments);
string pdfFolder = Path.Combine(documentsPath, "Generated PDFs");
Directory.CreateDirectory(pdfFolder);
string outputPath = Path.Combine(pdfFolder, $"{documentName}.pdf");
pdf.SaveAs(outputPath);
// Open PDF in default viewer without waiting for it to close
Process.Start(new ProcessStartInfo
{
FileName = outputPath,
UseShellExecute = true // Essential for opening PDF in default application
});
Console.WriteLine($"PDF opened: {outputPath}");
}
catch (Exception ex)
{
Console.WriteLine($"Error generating or opening PDF: {ex.Message}");
}
}
Imports IronPdf
Imports IronPdf.Rendering
Imports System.Diagnostics
Imports System.IO
Module PdfGenerator
Sub GenerateAndDisplayPdf(htmlContent As String, documentName As String)
Try
' Configure IronPDF renderer with production settings
Dim renderer As New ChromePdfRenderer With {
.RenderingOptions = New ChromePdfRenderOptions With {
.PaperSize = PdfPaperSize.A4,
.PrintHtmlBackgrounds = True,
.CreatePdfFormsFromHtml = True
}
}
' Generate the PDF
Dim pdf = renderer.RenderHtmlAsPdf(htmlContent)
' Use the user's Documents folder for better accessibility
Dim documentsPath As String = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
Dim pdfFolder As String = Path.Combine(documentsPath, "Generated PDFs")
Directory.CreateDirectory(pdfFolder)
Dim outputPath As String = Path.Combine(pdfFolder, $"{documentName}.pdf")
pdf.SaveAs(outputPath)
' Open PDF in default viewer without waiting for it to close
Process.Start(New ProcessStartInfo With {
.FileName = outputPath,
.UseShellExecute = True ' Essential for opening PDF in default application
})
Console.WriteLine($"PDF opened: {outputPath}")
Catch ex As Exception
Console.WriteLine($"Error generating or opening PDF: {ex.Message}")
End Try
End Sub
End Module
此範例包含結構化錯誤處理,並將 PDF 檔案保存在使用者的"文件"資料夾中,無論應用程式是如何啟動的,都可以存取該資料夾。 它還為 IronPDF 配置了適合商務文件的渲染選項:A4 紙張大小、啟用 HTML 背景列印以及從 HTML 表單元素自動建立表單欄位。
您可以在 IronPDF 的操作指南庫中了解更多關於互動式 PDF 表單和自訂浮水印的資訊。
此方法不會等待 PDF 檢視器關閉,從而允許應用程式在使用者查看文件時繼續運行。 根據微軟關於 Process.Start 的文檔,這種方法可以確保正確的資源管理,並防止應用程式阻塞在長時間運行的檢視器進程上。 Microsoft Learn 上的ProcessStartInfo 類別參考提供了您可以設定的屬性的完整列表,包括視窗樣式、動詞(開啟、列印)和工作目錄。
如何在 C# 中使用預設檢視器開啟 PDF:圖 3 - PDF 產生到檢視流程
配置渲染選項
ChromePdfRenderOptions 類別可讓您對輸出 PDF 進行精細控制。 常見設定包括:
- PaperSize -- 設定為
PdfPaperSize.A4、Letter或任何標準尺寸。 - PrintHtmlBackgrounds -- 從 HTML 渲染背景顏色和圖片。
- CreatePdfFormsFromHtml -- 將 HTML
<input>和<select>元素轉換為互動式 PDF 表單欄位。 - MarginTop / MarginBottom / MarginLeft / MarginRight -- 以毫米為單位控制頁面邊距。
這些設定同樣適用於渲染 HTML 字串、本機 HTML 檔案或遠端 URL。
如何從生成的PDF文件中提取數據?
產生並開啟 PDF 文件後,您可能還需要閱讀其內容。 IronPDF 支援從 PDF 文件中提取文本,這對於日誌記錄、驗證或下游處理非常有用。
對於包含大量影像的文檔,您也可以使用PDF 轉影像功能將單一頁面渲染為 PNG 或 JPEG 檔案。 這在預覽生成和縮圖工作流程中很常見。
這兩個功能都可透過同一個 IronPDF 庫實現,無需額外的依賴項。 完整的 IronPDF API 文件提供了所有提取和轉換操作的方法級參考。
如果沒有安裝PDF閱讀器會發生什麼事?
如果目標電腦上未安裝 PDF 檢視器,Windows 將顯示一個對話框,要求使用者選擇一個應用程式或造訪 Microsoft Store 尋找一個。 這是標準的 Windows 行為,不受 Process.Start 的控制。
為了在生產代碼中優雅地處理這種情況,您可以捕獲當找不到 .pdf 文件擴展名的已註冊處理程序時 Process.Start 拋出的 Win32Exception 異常:
using System.ComponentModel;
using System.Diagnostics;
try
{
Process.Start(new ProcessStartInfo
{
FileName = outputPath,
UseShellExecute = true
});
}
catch (Win32Exception ex) when (ex.NativeErrorCode == 1155)
{
// Error 1155: No application associated with the file extension
Console.WriteLine("No PDF viewer is installed. Please install a PDF reader such as Adobe Acrobat Reader.");
}
using System.ComponentModel;
using System.Diagnostics;
try
{
Process.Start(new ProcessStartInfo
{
FileName = outputPath,
UseShellExecute = true
});
}
catch (Win32Exception ex) when (ex.NativeErrorCode == 1155)
{
// Error 1155: No application associated with the file extension
Console.WriteLine("No PDF viewer is installed. Please install a PDF reader such as Adobe Acrobat Reader.");
}
Imports System.ComponentModel
Imports System.Diagnostics
Try
Process.Start(New ProcessStartInfo With {
.FileName = outputPath,
.UseShellExecute = True
})
Catch ex As Win32Exception When ex.NativeErrorCode = 1155
' Error 1155: No application associated with the file extension
Console.WriteLine("No PDF viewer is installed. Please install a PDF reader such as Adobe Acrobat Reader.")
End Try
錯誤代碼 1155 對應 ERROR_NO_ASSOCIATION,當沒有應用程式註冊該檔案類型時,Windows 會傳回此錯誤代碼。 捕獲到這個特定錯誤後,可以顯示有用的消息,而不是導致程式崩潰。 完整的 Windows 系統錯誤代碼清單記錄在 Microsoft Learn 上的Win32 錯誤代碼參考文件中。
如何選擇合適的申請方式?
開啟 PDF 檔案的方法取決於您正在建立的應用程式類型:
| 應用程式類型 | 建議的翻譯方法 | 關鍵考慮因素 |
|---|---|---|
| 控制台或桌面應用程式 | Process.Start 時 UseShellExecute = true | 簡單,無需額外依賴 |
| Windows 服務 | 儲存到磁碟;透過進程間通訊或訊息佇列通知用戶 | 服務無需桌面會話即可運行 |
| Web應用程式(ASP.NET) | 以文件下載或直接在瀏覽器中查看 PDF 流 | Process.Start 在 Web 伺服器上下文中無效。 |
| MAUI 或 WinForms | 處理.啟動或嵌入式 PDF 控件 | 嵌入式觀看可帶來更佳的應用程式內體驗 |
對於使用 ASP.NET Core 建立的 Web 應用程序,請勿使用 Process.Start。 伺服器進程在無頭環境下運行,無法開啟桌面應用程式。 相反,使用 File() 和 application/pdf MIME 類型將 PDF 作為文件結果返回,並讓瀏覽器處理顯示。
對於控制台和桌面應用程序,使用 Process.Start 和 UseShellExecute = true 仍然是最簡單、最可靠的選擇。
準備好在 .NET 應用程式中開始產生和查看 PDF 文件了嗎? 您可以先免費試用以存取全部功能,或查看IronPDF 授權頁面,找到適合您專案的方案。
常見問題解答
如何使用C#在預設檢視器中打開PDF?
您可以使用IronPDF生成PDF,並使用System.Diagnostics.Process.Start在用戶的預設PDF應用程式中打開它,以在C#中打開PDF。
什麼是IronPDF?
IronPDF是一個.NET庫,允許開發者在其應用程式中程序化創建、編輯和操作PDF文件。
使用 IronPDF 有哪些系統要求?
IronPDF與任何.NET應用程式兼容,並在Windows、macOS和Linux平台上工作。它需要安裝.NET Framework或.NET Core/5+。
IronPDF能否默認在Adobe Acrobat中打開PDF?
是的,IronPDF可以生成在用戶設置的預設PDF檢視器中打開的PDF,這可以是Adobe Acrobat、Microsoft Edge或其他任何PDF查看應用。
System.Diagnostics.Process.Start如何與IronPDF一起工作?
System.Diagnostics.Process.Start用於在預設檢視器中打開生成的PDF文件。一旦IronPDF創建了文件,此方法就會啟動與PDF文件相關聯的預設應用程式來顯示它。
是否可以用IronPDF編輯PDF文件?
是的,IronPDF允許您在保存或顯示之前通過添加文字、圖片、註釋等來編輯現有的PDF文件。
IronPDF支援哪些編程語言?
IronPDF主要與C#一起使用,但也可以整合到使用VB.NET和其他.NET支援語言的項目中。
IronPDF能否在生成PDF後自動化顯示?
是的,在使用IronPDF生成PDF後,您可以使用System.Diagnostics.Process.Start來自動打開它,以便即時在用戶的預設檢視器中顯示。
使用IronPDF是否有可用的代碼範例?
IronPDF文檔提供各種生成和操作PDF的代碼範例,包括如何使用C#在預設檢視器中打開它們。
IronPDF有哪些常見的使用案例?
IronPDF的常見使用案例包括生成報告、發票和其他文檔,將HTML轉換為PDF,以及在.NET應用程式中自動化PDF顯示過程。
IronPDF是否與.NET 10兼容,這帶來了哪些好處?
是的。IronPDF完全兼容.NET 10,包括其運行時和語言增強。使用IronPDF搭配.NET 10可讓您的應用受益於性能提升,例如減少堆分配、加快PDF生成和與現代API和平台更順暢的集成。



