Windows Forms: How to Read a PDF file in C#

How to read a PDF file using iTextSharp in C#.

Step 1Click New Project, then select Visual C# on the left, then Windows and then select Windows Forms Application. Name your project "PdfReader" and then click OK

c# read pdf fileStep 2: Right click on your project select Manage NuGet Packages -> Search itextsharp -> Install

install itextsharp

iText is a PDF library that allows you to CREATE, ADAPT, INSPECT and MAINTAIN documents in the Portable Document Format, allowing you to add PDF functionality to your software projects with ease.

Step 3: Design your form as below

read pdf in c#

Step 4: Add code to handle your form

using iTextSharp.text.pdf.parser;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace PdfReader
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btnOpen_Click(object sender, EventArgs e)
        {
            using(OpenFileDialog ofd = new OpenFileDialog() { Filter="PDF files|*.pdf", ValidateNames = true, Multiselect = false })
            {
                if(ofd.ShowDialog() == DialogResult.OK)
                {
                    try
                    {
                        iTextSharp.text.pdf.PdfReader reader = new iTextSharp.text.pdf.PdfReader(ofd.FileName);
                        StringBuilder sb = new StringBuilder();
                        for(int i = 1; i <= reader.NumberOfPages; i++)
                        {
                            //Read page
                            sb.Append(PdfTextExtractor.GetTextFromPage(reader, i));
                        }
                        richTextBox.Text = sb.ToString();
                        reader.Close();
                    }
                    catch(Exception ex)
                    {
                        MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
        }
    }
}

VIDEO TUTORIALS