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:

  1. The program determines the executable's directory using Application.StartupPath.
  2. It appends the file path to the Test.pdf file using Path.Combine.
  3. It navigates the WebBrowser control (webPdf) to the full path of the PDF file, and the PDF file is displayed in the control.