How to Open a PDF file in C#
By FoxLearn 1/9/2025 6:29:45 AM 178
In this article, we will explore how to display a PDF file in a WebBrowser control in a Windows Forms application.
At design time, we add a WebBrowser control to the form and set up some code that will enable the WebBrowser to open and display a PDF file when the program starts. Name it webPdf
Add the PDF File to the Project
- Place the PDF file you want to display (e.g.,
Test.pdf
) into your project directory. - In the Solution Explorer, right-click on the file
Test.pdf
and select Properties. - Set the Copy to Output Directory property to Copy if newer. This ensures that the PDF file is copied to the executable’s output directory when the project is built.
Go to your Form1_Load
event, and add the following code:
// open pdf in c# private void Form1_Load(object sender, EventArgs e) { // Get the path of the executable's directory. string filename = Application.StartupPath; // Append the file name to the directory path. filename = Path.GetFullPath(Path.Combine(filename, ".\\Test.pdf")); // Navigate the WebBrowser control to the PDF file. webPdf.Navigate(filename); }
When you start the application:
- The program determines the executable's directory using
Application.StartupPath
. - It appends the file path to the
Test.pdf
file usingPath.Combine
. - It navigates the WebBrowser control (
webPdf
) to the full path of the PDF file, and the PDF file is displayed in the control.
- Using the OrderBy and OrderByDescending in LINQ
- Querying with LINQ
- Optimizing Performance with Compiled Queries in LINQ
- MinBy() and MaxBy() Extension Methods in .NET
- SortBy, FilterBy, and CombineBy in NET 9
- Exploring Hybrid Caching in .NET 9.0
- Using Entity Framework with IDbContext in .NET 9.0
- Primitive types in C#