SoFunction
Updated on 2025-03-07

C# Method to obtain the specified number of PDF pages

This article describes the method of obtaining the specified number of PDF pages in C#. Share it for your reference. The details are as follows:

using System;
using ;
using ;
using ;
namespace RobvanderWoude
{
 class PDFPageCount
 {
  static int Main( string[] args )
  {
   #region Get help
   if (  == 0 )
   {
    ShowHelp( );
    return 0;
   }
   foreach ( string arg in args )
   {
    if ( arg == "/?" || arg == "-?" || ( ) == "--help" )
    {
     ShowHelp( );
     return 0;
    }
   }
   #endregion
   int errors = 0;
   foreach ( string arg in args )
   {
    try
    {
     Regex regexp = new Regex( @"^(.*)\\([^\\]+\.pdf)$",  );
     if ( ( arg ) )
     {
      // Match means the filespec has a valid format (. *.pdf)
      string[] matches = ( arg );
      string folder = matches[1];
      string filespec = matches[2];
      if ( ( folder ) )
      {
       // Folder exists, check for matching files
       string[] fileList = ( folder, filespec );
       if (  == 0 )
       {
        // No matching files in this folder
        ShowError( "ERROR: No files matching \"{0}\" were found in \"{1}\"", filespec, folder );
        errors += 1;
       }
       else
       {
        // Iterate through list of matching files
        foreach ( string file in fileList )
        {
         int pagecount = PageCount( file );
         if ( pagecount == -1 )
         {
          // Just increase the error count, the PageCount( )
          // procedure already wrote an error message to screen
          errors += 1;
         }
         else
         {
          // No pages means there is a problem with the file
          if ( pagecount == 0 )
          {
            = ;
           errors += 1;
          }
          // Display the formated result on screen
          ( "{0,4} {1,-10} {2}", ( ), ( pagecount == 1 ? "page" : "pages" ), file );
          if ( pagecount == 0 )
          {
            = ;
          }
         }
        }
       }
      }
      else
      {
       // Folder doesn't exist
       ShowError( "ERROR: Folder \"{0}\" not found", folder );
       errors += 1;
      }
     }
     else
     {
      // No match for the regular expression means the filespec was invalid
      ShowError( "ERROR: Invalid filespec \"{0}\", please specify PDF files only", arg );
      errors += 1;
     }
    }
    catch ( Exception e )
    {
     // All other errors: display an error message and then continue
     ShowError( "ERROR: {0}",  );
     errors += 1;
    }
   }
   if ( errors != 0 )
   {
    ShowError( "    {0} finished with {1} error{2}", GetExeName( ), ( ), ( errors == 1 ? "" : "s" ) );
   }
   return errors;
  }
  static string GetExeName( )
  {
   string exe = ( );
   Regex regexp = new Regex( @"\\([^\\]+)$" );
   return ( exe )[1];
  }
  static int PageCount( string filename )
  {
   Regex regexp = new Regex( @"\.pdf$",  );
   if ( ( filename ) )
   {
    try
    {
     FileStream fs = new FileStream( filename, ,  );
     StreamReader sr = new StreamReader( fs );
     string pdfText = ( );
     regexp = new Regex( @"/Type\s*/Page[^s]" );
     MatchCollection matches = ( pdfText );
     return ;
    }
    catch ( Exception e )
    {
     ShowError( "ERROR: {0} ({1})", , filename );
     return -1;
    }
   }
   else
   {
    ShowError( "ERROR: {0} is not a PDF file", filename );
    return -1;
   }
  }
  static void ShowError( string message, string param1, string param2 = "", string param3 = "" )
  {
   ( );
    = ;
   ( message, param1, param2, param3 );
    = ;
   ( );
  }
  #region Display help text
  static void ShowHelp( )
  {
   ( );
   ( "{0}, Version 1.02", GetExeName( ) );
   ( "Return the page count for the specified PDF file(s)" );
   ( );
   ( "Usage: {0} filespec [ filespec [ filespec [ ... ] ] ]", GetExeName( ).ToUpper( ) );
   ( );
   ( "Where: \"filespec\"  is a file specification for the PDF file(s) to" );
   ( "       be listed (wildcards * and ? are allowed)" );
   ( );
   ( "Note:  The program's return code equals the number of errors encountered." );
   ( );
   ( "Written by Rob van der Woude" );
  }
  #endregion
 }
}

I hope this article will be helpful to everyone's C# programming.