How to Open a PDF file in C#
By FoxLearn 1/9/2025 6:29:45 AM 96
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.
- How to fix 'Failure sending mail' in C#
- How to Parse a Comma-Separated String from App.config in C#
- How to convert a dictionary to a list in C#
- How to retrieve the Executable Path in C#
- How to validate an IP address in C#
- How to retrieve the Downloads Directory Path in C#
- C# Tutorial
- Dictionary with multiple values per key in C#
Categories
Popular Posts
AdminKit Bootstrap 5 HTML5 UI Kits Template
11/17/2024
Spica Admin Dashboard Template
11/18/2024