Monday, July 25, 2011

C# code to count number of page in PDF file

CODE::
 

using System.IO;

using System.Text.RegularExpressions;

  

Drag one label, two buttons, one fileOpenDialog object and one textbox on the form.


Now write following code on form Load event




private void Form1_Load(object sender, EventArgs e)



        {



            this.Text = "DevAsp PDF Page Counter";



            button1.Text = "Browse";



            button2.Text = "Count Pages";



        }
 

Now write code on buttons events



private void button2_Click(object sender, EventArgs e)



        {



            MessageBox.Show(GetNoOfPagesPDF(textBox1.Text).ToString());



        }

  

private void button1_Click(object sender, EventArgs e)



        {



            if (openFileDialog1.ShowDialog() == DialogResult.OK)



            {



                textBox1.Text = openFileDialog1.FileName;



            }



        }




Now this is the function which count pages of PDF
 

public static int GetNoOfPagesPDF(string FileName)

        {



            int result = 0;


            FileStream fs = new FileStream(FileName, FileMode.Open, FileAccess.Read);
 

            StreamReader r = new StreamReader(fs);
 

            string pdfText = r.ReadToEnd();
 

            System.Text.RegularExpressions.Regex regx = new Regex(@"/Type\s*/Page[^s]");
 

            System.Text.RegularExpressions.MatchCollection matches = regx.Matches(pdfText);


            result = matches.Count;

             return result;


        }

  

In this funciton we are opening PDF file. and then using aDoc. Regex(@"/Type\s*/Page[^s]"); function we count total pages of PDF file.




No comments:

Post a Comment