Rob van der Woude's Scripting Pages
Powered by GeSHi

Source code for pdfpagecount.cs

(view source code of pdfpagecount.cs as plain text)

  1. using System;
  2. using System.IO;
  3. using System.Text.RegularExpressions;
  4. using System.Windows.Forms;
  5.  
  6. namespace RobvanderWoude
  7. {
  8. 	class PDFPageCount
  9. 	{
  10. 		static int Main( string[] args )
  11. 		{
  12. 			#region Get help
  13.  
  14. 			if ( args.Length == 0 )
  15. 			{
  16. 				ShowHelp( );
  17. 				return 0;
  18. 			}
  19.  
  20. 			foreach ( string arg in args )
  21. 			{
  22. 				if ( arg == "/?" || arg == "-?" || arg.ToLower( ) == "--help" )
  23. 				{
  24. 					ShowHelp( );
  25. 					return 0;
  26. 				}
  27. 			}
  28.  
  29. 			#endregion
  30.  
  31. 			int errors = 0;
  32.  
  33. 			foreach ( string arg in args )
  34. 			{
  35. 				try
  36. 				{
  37. 					Regex regexp = new Regex( @"^(.*)\\([^\\]+\.pdf)$", RegexOptions.IgnoreCase );
  38. 					if ( regexp.IsMatch( arg ) )
  39. 					{
  40. 						// Match means the filespec has a valid format (i.e. *.pdf)
  41. 						string[] matches = regexp.Split( arg );
  42. 						string folder = matches[1];
  43. 						string filespec = matches[2];
  44. 						if ( Directory.Exists( folder ) )
  45. 						{
  46. 							// Folder exists, check for matching files
  47. 							string[] fileList = Directory.GetFiles( folder, filespec );
  48. 							if ( fileList.Length == 0 )
  49. 							{
  50. 								// No matching files in this folder
  51. 								ShowError( "ERROR: No files matching \"{0}\" were found in \"{1}\"", filespec, folder );
  52. 								errors += 1;
  53. 							}
  54. 							else
  55. 							{
  56. 								// Iterate through list of matching files
  57. 								foreach ( string file in fileList )
  58. 								{
  59. 									int pagecount = PageCount( file );
  60. 									if ( pagecount == -1 )
  61. 									{
  62. 										// Just increase the error count, the PageCount( )
  63. 										// procedure already wrote an error message to screen
  64. 										errors += 1;
  65. 									}
  66. 									else
  67. 									{
  68. 										// No pages means there is a problem with the file
  69. 										if ( pagecount == 0 )
  70. 										{
  71. 											Console.ForegroundColor = ConsoleColor.Red;
  72. 											errors += 1;
  73. 										}
  74. 										// Display the formated result on screen
  75. 										Console.WriteLine( "{0,4} {1,-10} {2}", pagecount.ToString( ), ( pagecount == 1 ? "page" : "pages" ), file );
  76. 										if ( pagecount == 0 )
  77. 										{
  78. 											Console.ForegroundColor = ConsoleColor.Gray;
  79. 										}
  80. 									}
  81. 								}
  82. 							}
  83. 						}
  84. 						else
  85. 						{
  86. 							// Folder doesn't exist
  87. 							ShowError( "ERROR: Folder \"{0}\" not found", folder );
  88. 							errors += 1;
  89. 						}
  90. 					}
  91. 					else
  92. 					{
  93. 						// No match for the regular expression means the filespec was invalid
  94. 						ShowError( "ERROR: Invalid filespec \"{0}\", please specify PDF files only", arg );
  95. 						errors += 1;
  96. 					}
  97. 				}
  98. 				catch ( Exception e )
  99. 				{
  100. 					// All other errors: display an error message and then continue
  101. 					ShowError( "ERROR: {0}", e.Message );
  102. 					errors += 1;
  103. 				}
  104. 			}
  105.  
  106. 			if ( errors != 0 )
  107. 			{
  108. 				ShowError( "                {0} finished with {1} error{2}", GetExeName( ), errors.ToString( ), ( errors == 1 ? "" : "s" ) );
  109. 			}
  110. 			return errors;
  111. 		}
  112.  
  113.  
  114. 		static string GetExeName( )
  115. 		{
  116. 			string exe = Application.ExecutablePath.ToString( );
  117. 			Regex regexp = new Regex( @"\\([^\\]+)$" );
  118. 			return regexp.Split( exe )[1];
  119. 		}
  120.  
  121.  
  122. 		static int PageCount( string filename )
  123. 		{
  124. 			//Function for finding the number of pages in a given PDF file, based on
  125. 			// http://www.dotnetspider.com/resources/21866-Count-pages-PDF-file.aspx
  126.  
  127. 			Regex regexp = new Regex( @"\.pdf$", RegexOptions.IgnoreCase );
  128. 			if ( regexp.IsMatch( filename ) )
  129. 			{
  130. 				try
  131. 				{
  132. 					FileStream fs = new FileStream( filename, FileMode.Open, FileAccess.Read );
  133. 					StreamReader sr = new StreamReader( fs );
  134. 					string pdfText = sr.ReadToEnd( );
  135. 					regexp = new Regex( @"/Type\s*/Page[^s]" );
  136. 					MatchCollection matches = regexp.Matches( pdfText );
  137. 					return matches.Count;
  138. 				}
  139. 				catch ( Exception e )
  140. 				{
  141. 					ShowError( "ERROR: {0} ({1})", e.Message, filename );
  142. 					return -1;
  143. 				}
  144. 			}
  145. 			else
  146. 			{
  147. 				ShowError( "ERROR: {0} is not a PDF file", filename );
  148. 				return -1;
  149. 			}
  150. 		}
  151.  
  152.  
  153. 		static void ShowError( string message, string param1, string param2 = "", string param3 = "" )
  154. 		{
  155. 			Console.Error.WriteLine( );
  156. 			Console.ForegroundColor = ConsoleColor.Red;
  157. 			Console.Error.WriteLine( message, param1, param2, param3 );
  158. 			Console.ForegroundColor = ConsoleColor.Gray;
  159. 			Console.Error.WriteLine( );
  160. 		}
  161.  
  162.  
  163. 		#region Display help text
  164.  
  165. 		static void ShowHelp( )
  166. 		{
  167. 			Console.Error.WriteLine( );
  168. 			Console.Error.WriteLine( "{0},  Version 1.02", GetExeName( ) );
  169. 			Console.Error.WriteLine( "Return the page count for the specified PDF file(s)" );
  170. 			Console.Error.WriteLine( );
  171. 			Console.Error.WriteLine( "Usage:  {0}  filespec  [ filespec  [ filespec  [ ... ] ] ]", GetExeName( ).ToUpper( ) );
  172. 			Console.Error.WriteLine( );
  173. 			Console.Error.WriteLine( "Where:  \"filespec\"        is a file specification for the PDF file(s) to" );
  174. 			Console.Error.WriteLine( "                          be listed (wildcards * and ? are allowed)" );
  175. 			Console.Error.WriteLine( );
  176. 			Console.Error.WriteLine( "Note:   The program's return code equals the number of errors encountered." );
  177. 			Console.Error.WriteLine( );
  178. 			Console.Error.WriteLine( "Written by Rob van der Woude" );
  179. 			Console.Error.WriteLine( "http://www.robvanderwoude.com" );
  180. 		}
  181.  
  182. 		#endregion
  183. 	}
  184. }
  185.  

page last modified: 2024-04-16; loaded in 0.0356 seconds