How to Open a PDF file in C#
By FoxLearn 1/9/2025 6:29:45 AM 291
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.
- Primitive types in C#
- How to set permissions for a directory in C#
- How to Convert Int to Byte Array in C#
- How to Convert string list to int list in C#
- How to convert timestamp to date in C#
- How to Get all files in a folder in C#
- How to use Channel as an async queue in C#
- Case sensitivity in JSON deserialization
Categories
Popular Posts
Freedash bootstrap lite
11/13/2024
RuangAdmin Template
11/17/2024
AdminKit Bootstrap 5 HTML5 UI Kits Template
11/17/2024
Horizon MUI Admin Dashboard Template
11/18/2024