How to Start Tutorials Troubleshooting Main Operations Convert PDF Read PDF Edit PDF PDF Report Generator Work with PDF Modules PDF Document PDF Pages Text Image Graph & Path Annotation, Markup & Drawing Redaction Security Digital Signature Forms Watermark Bookmark Link File Attachment File Metadata Printing Work with Other SDKs Barcode read Barcode create OCR Twain

WinForms PDF Viewer C# Library
How to read, view PDF file in C# .NET Windows Forms application?


Complete step by step tutorial to view PDFs with page navigation, zooming in .NET WinForms application using C#.



This C# tutorial will show how to load and display PDF files on .NET Windows Forms application.

At the end of the tutorial, you'll have a WinForms window app that reads and displays a PDF document on .NET windows forms. You will learn how to:

  • Create a new WinForms app
  • View PDF pages on Window form
  • Navigate PDF through pages and adjust viewing mode



Download and Install XDoc.PDF WPF C# library


  1. Download XDoc.PDF WPF C# library
  2. Install C# library to read, view, navigate PDF files in .NET Core WPF projects
  3. Step by Step Tutorial






How to view PDF on Windows Forms (.NET) using C# in Windows application?



1. Create a new .NET Windows Forms project with XDoc.PDF C# library

Now we will create a new Windows Forms App project with name "REPDFViewerWinFormDemo".

We have show detailed guide to integrate XDoc.PDF library on a new created WinForms (.NET Core) project. Please view here:
How to create a new WinForms app using Visual Studio 2022 to view, edit PDF?





2. Use Toolbox to add controls to the form "Form1".

Before add any controls, changes the property Size of control "Form1" to "816, 700" in the Properties window first.

List of controls to add (in turn)

  1. A Panel for setting
  2. A Panel for viewing
  3. A Button for opening a file
  4. A Combobox for selecting page to view
  5. A Combobox for choosing view mode
  6. An OpenFileDialog



2.1 add a Panel control to the Form.



Then change property Name to "panelViewSetting", property Dock to "Bottom", and property Size to "800, 50".



2.2 add another Panel control to the Form.



Then change property Name to "panelView", property Dock to "Fill", property BackColor to "AppWorkspace", and property AutoScroll to "True".



2.3 add a Button control to Panel "panelViewSetting".



Then change the new button property Text to "Open File".



2.4 add a ComboBox control to Panel "panelViewSetting".



Then change property Name to "comboBoxPageNumber", property Anchor to "Top, Right", property Location to "560, 15", and property Size to "80, 23".



2.5 add another ComboBox control to Panel "panelViewSetting".



Then change property Name to "comboBoxViewMode", property Anchor to "Top, Right", property Location to "646, 15", and property Size to "135, 23".



2.6 add a PictureBox control to Panel "panelView".



2.7 add an OpenFileDialog control to Form.





3. Add events to buttons.

Double click Button control "button1" to add Click event "button1_Click".



Double click ComboBox control "comboBoxPageNumber" to add SelectedIndexChanged event "comboBoxPageNumber_SelectedIndexChanged".



Double click ComboBox control "comboBoxViewMode" to add SelectedIndexChanged event "comboBoxViewMode_SelectedIndexChanged".



Finally, select main Form control to add Resize event "Form1_Resize".





4. Add code to the form

Select "View Code" from the menu to open the Form1.cs window.





Replace all contents in the Form1.cs file by following C# codes.

using RasterEdge.Imaging.Basic;
using RasterEdge.XDoc.PDF;

namespace REPDFViewerWinFormDemo
{
    public partial class Form1 : Form
    {
        private String _targetFilePath = "";
        private String _currPageViewMode;
        private Bitmap _cachedPageImage = new Bitmap(1, 1);
        private float _cachedPageZoomRatio = 4F;

        public Form1()
        {
            InitializeComponent();
            initialViewSettingControls();
            this._currPageViewMode = this.comboBoxViewMode.Text;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            this.openFileDialog1.Filter = "PDF files (*.pdf)|*.pdf";
            if (this.openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    String filePath = this.openFileDialog1.FileName;
                    if (String.IsNullOrEmpty(filePath))
                        throw new Exception("Target file path is null or empty.");
                    if (!File.Exists(filePath))
                        throw new Exception("Target file does not exist.");

                    PDFDocument doc = new PDFDocument(filePath);
                    int pageCount = doc.GetPageCount();
                    if (pageCount <= 0)
                        throw new Exception("Load PDF file failed. Page count must be positive.");

                    setAndEnableViewSettingControls(pageCount);

                    this._targetFilePath = filePath;
                    this._currPageViewMode = this.comboBoxViewMode.Text;

                    this.Text = filePath;

                    updateCachedPageImage(this.comboBoxPageNumber.SelectedIndex);
                    updatePageView();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

        private void comboBoxPageNumber_SelectedIndexChanged(object sender, EventArgs e)
        {
            updateCachedPageImage(this.comboBoxPageNumber.SelectedIndex);
            updatePageView();
        }

        private void comboBoxViewMode_SelectedIndexChanged(object sender, EventArgs e)
        {
            this._currPageViewMode = this.comboBoxViewMode.Text;
            updatePageView();
        }

        private void Form1_Resize(object sender, EventArgs e)
        {
            updatePageView();
        }

        private void initialViewSettingControls()
        {
            //  Initial controls and properties.
            this.comboBoxPageNumber.Enabled = false;
            this.comboBoxViewMode.Enabled = false;
            this.comboBoxViewMode.Items.AddRange(new object[] {
                "Actual Size",
                "Zoom to Page Level",
                "Fit Width"
            });
            this.comboBoxViewMode.SelectedIndex = 0;
        }

        private void setAndEnableViewSettingControls(int pageCount)
        {
            this.comboBoxPageNumber.Items.Clear();
            List<object> list = new List<object>();
            for (int i = 1; i <= pageCount; i++)
                list.Add("Page " + i);
            this.comboBoxPageNumber.Items.AddRange(list.ToArray());
            this.comboBoxPageNumber.SelectedIndex = 0;
            this.comboBoxPageNumber.Enabled = true;
            this.comboBoxViewMode.SelectedIndex = 0;
            this.comboBoxViewMode.Enabled = true;
        }

        public bool HasTargetFile
        {
            get { return !String.IsNullOrEmpty(this._targetFilePath); }
        }

        private void updateCachedPageImage(int pageIndex)
        {
            if (!HasTargetFile) return;
            try
            {
                PDFDocument doc = new PDFDocument(this._targetFilePath);
                BasePage page = doc.GetPage(pageIndex);
                //  Get page size in inch.
                float pageWidth = page.GetWidth();
                float pageHeight = page.GetHeight();
                //  Zoom ratio used in page renderring.
                //  Default: 4
                float zoomRatio = 4F;
                //  Set to small value if page size is too large.
                if (pageWidth > 12F || pageHeight > 12F)
                    zoomRatio = 2;
                else if (pageWidth > 20F || pageHeight > 20F)
                    zoomRatio = 1;

                Bitmap image = page.GetBitmap(zoomRatio);
                setCachecPageImage(image, zoomRatio);
            }
            catch (Exception)
            {
                setCachecPageImage(new Bitmap(1, 1), 4F);
            }
        }

        private void setCachecPageImage(Bitmap image, float zoomRatio)
        {
            this._cachedPageImage = image;
            this._cachedPageZoomRatio = zoomRatio;
        }

        private void updatePageView()
        {
            if (!HasTargetFile)
                return;
            if (this._cachedPageImage == null)
                return;

            float canvasWidth = this.panelView.Width - 20;
            float canvasHeight = this.panelView.Height;

            //  Estimate show image size.
            float imageWidth = this._cachedPageImage.Width;
            float imageHeight = this._cachedPageImage.Height;
            float zoomRatio = 1F;
            switch (this._currPageViewMode)
            {
                case "Zoom to Page Level":
                    zoomRatio = Math.Min(canvasWidth / imageWidth, canvasHeight / imageHeight);
                    break;
                case "Fit Width":
                    zoomRatio = canvasWidth / imageWidth;
                    break;
                case "Actual Size":
                    zoomRatio = 1F / this._cachedPageZoomRatio;
                    break;
                default:
                    break;
            }
            imageWidth *= zoomRatio;
            imageHeight *= zoomRatio;

            Bitmap bitmap = new Bitmap((int)imageWidth, (int)imageHeight);
            using (Graphics g = Graphics.FromImage(bitmap))
            {
                g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                g.DrawImage(this._cachedPageImage, 0, 0, bitmap.Width, bitmap.Height);
            }

            this.pictureBox1.Image = bitmap;
            this.pictureBox1.Width = bitmap.Width;
            this.pictureBox1.Height = bitmap.Height;
            int x = 0;
            if (canvasWidth >= imageWidth)
                x = (int)((canvasWidth - imageWidth) / 2F);
            this.pictureBox1.Location = new Point(x, 0);
        }
    }
}



Then final class Form1 would be looks like below.





5. It is done. Now press "Ctrl+F5" to run the project.





6. Screenshot for the WinForms PDF Viewer demo application.



Press "Open File" button to select an existing PDF file from your local computer system through the open file dialog. Then, it shows the first page of the selected PDF file in "Actual Size" viewing mode.



Use two ComboBox controls to change the selected PDF page number and viewing mode.





Conclusion

Now you have created a Windows Forms application to load and view PDFs on form. It is for demo purpose, and you can further improve it by performance tuning, adding more PDF viewing, navigating, converting functions.

RasterEdge has a high quality and easy to use web version Acrobat for ASP.NET web app: ASP.NET PDF Viewer and Editor web control.

You could view the details here:
How to view, edit PDF file in web browser using C# ASP.NET?