Open a PDF file in C#


[Open a PDF file]

At design time I added a WebBrowser control to the form. When the program starts it uses the following code to open a PDF file in a WebBrowser control.

// Display the PDF file.
private void Form1_Load(object sender, EventArgs e)
{
    string filename = Application.StartupPath;
    filename = Path.GetFullPath(
        Path.Combine(filename, ".\\Test.pdf"));
    wbrPdf.Navigate(filename);
}

At design time I added that file to the project and set its “Copy to Output Directory” property to “Copy if newer” so the file will be in the executable program’s directory.

This code gets the program’s startup directory and adds the file name Test.pdf. It then makes the wbrPdf WebBrowser control navigate to that file.


Download Example   Follow me on Twitter   RSS feed   Donate




This entry was posted in controls and tagged , , , , , , , , . Bookmark the permalink.

6 Responses to Open a PDF file in C#

  1. Richard Payne says:

    I have created a PDF from word document and wish to know how to jump to header after opening the webrowser

  2. Ziz says:

    I tried this today in Win10 with VS2017 but find it does not work. Maybe you have set something in your environment to make it open in the app. Today all I can get it to do is save the file to disk.

    • RodStephens says:

      Did the program run and fail? If so, what’s the error message?

      Be sure you unzipped the project. (Some people try to run projects inside the zip file. Visual Studio looks like it’s trying but it doesn’t work.) Also make sure the PDF file is copied into the executable directory so the program can find it.

      Otherwise I don’t know why it wouldn’t work. You should only need permission to read the PDF file.

      It works for me with Windows 10 Home 1903 and these:

      • C# 2008
      • Visual Studio Community 2019 v 16.0.3
      • Visual Studio Community 2019 v 16.2.5
  3. Ziz says:

    It is unzipped. Compiles and runs but When I run the main winform that contains the webbrowser component it says “Navigation to the website was cancelled” and I get two other dialogs that open for “File Download” if I download I get the pdf file just does not show inside the Winform dialog. Must be a setting somewhere I need to turn on\off? Do you have something like an interop or PDF ticked in references?

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.