注册 登录
  • 欢迎访问开心洋葱网站,在线教程,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站,欢迎加入开心洋葱 QQ群
  • 为方便开心洋葱网用户,开心洋葱官网已经开启复制功能!
  • 欢迎访问开心洋葱网站,手机也能访问哦~欢迎加入开心洋葱多维思维学习平台 QQ群
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏开心洋葱吧~~~~~~~~~~~~~!
  • 由于近期流量激增,小站的ECS没能经的起亲们的访问,本站依然没有盈利,如果各位看如果觉着文字不错,还请看官给小站打个赏~~~~~~~~~~~~~!

C#获取指定PDF文件的页数

OC/C/C++ 水墨上仙 2298次浏览 已收录 手机上查看

此代码可以返回指定PDF文件有多少页

using System;
using System.IO;
using System.Text.RegularExpressions;
using System.Windows.Forms;
namespace RobvanderWoude
{
	class PDFPageCount
	{
		static int Main( string[] args )
		{
			#region Get help
			if ( args.Length == 0 )
			{
				ShowHelp( );
				return 0;
			}
			foreach ( string arg in args )
			{
				if ( arg == "/?" || arg == "-?" || arg.ToLower( ) == "--help" )
				{
					ShowHelp( );
					return 0;
				}
			}
			#endregion
			int errors = 0;
			foreach ( string arg in args )
			{
				try
				{
					Regex regexp = new Regex( @"^(.*)\\([^\\]+\.pdf)$", RegexOptions.IgnoreCase );
					if ( regexp.IsMatch( arg ) )
					{
						// Match means the filespec has a valid format (i.e. *.pdf)
						string[] matches = regexp.Split( arg );
						string folder = matches[1];
						string filespec = matches[2];
						if ( Directory.Exists( folder ) )
						{
							// Folder exists, check for matching files
							string[] fileList = Directory.GetFiles( folder, filespec );
							if ( fileList.Length == 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 )
										{
											Console.ForegroundColor = ConsoleColor.Red;
											errors += 1;
										}
										// Display the formated result on screen
										Console.WriteLine( "{0,4} {1,-10} {2}", pagecount.ToString( ), ( pagecount == 1 ? "page" : "pages" ), file );
										if ( pagecount == 0 )
										{
											Console.ForegroundColor = ConsoleColor.Gray;
										}
									}
								}
							}
						}
						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}", e.Message );
					errors += 1;
				}
			}
			if ( errors != 0 )
			{
				ShowError( "                {0} finished with {1} error{2}", GetExeName( ), errors.ToString( ), ( errors == 1 ? "" : "s" ) );
			}
			return errors;
		}
		static string GetExeName( )
		{
			string exe = Application.ExecutablePath.ToString( );
			Regex regexp = new Regex( @"\\([^\\]+)$" );
			return regexp.Split( exe )[1];
		}
		static int PageCount( string filename )
		{
			//Function for finding the number of pages in a given PDF file, based on
			// http://www.dotnetspider.com/resources/21866-Count-pages-PDF-file.aspx
			Regex regexp = new Regex( @"\.pdf$", RegexOptions.IgnoreCase );
			if ( regexp.IsMatch( filename ) )
			{
				try
				{
					FileStream fs = new FileStream( filename, FileMode.Open, FileAccess.Read );
					StreamReader sr = new StreamReader( fs );
					string pdfText = sr.ReadToEnd( );
					regexp = new Regex( @"/Type\s*/Page[^s]" );
					MatchCollection matches = regexp.Matches( pdfText );
					return matches.Count;
				}
				catch ( Exception e )
				{
					ShowError( "ERROR: {0} ({1})", e.Message, 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 = "" )
		{
			Console.Error.WriteLine( );
			Console.ForegroundColor = ConsoleColor.Red;
			Console.Error.WriteLine( message, param1, param2, param3 );
			Console.ForegroundColor = ConsoleColor.Gray;
			Console.Error.WriteLine( );
		}
		#region Display help text
		static void ShowHelp( )
		{
			Console.Error.WriteLine( );
			Console.Error.WriteLine( "{0},  Version 1.02", GetExeName( ) );
			Console.Error.WriteLine( "Return the page count for the specified PDF file(s)" );
			Console.Error.WriteLine( );
			Console.Error.WriteLine( "Usage:  {0}  filespec  [ filespec  [ filespec  [ ... ] ] ]", GetExeName( ).ToUpper( ) );
			Console.Error.WriteLine( );
			Console.Error.WriteLine( "Where:  \"filespec\"        is a file specification for the PDF file(s) to" );
			Console.Error.WriteLine( "                          be listed (wildcards * and ? are allowed)" );
			Console.Error.WriteLine( );
			Console.Error.WriteLine( "Note:   The program's return code equals the number of errors encountered." );
			Console.Error.WriteLine( );
			Console.Error.WriteLine( "Written by Rob van der Woude" );
			Console.Error.WriteLine( "http://www.robvanderwoude.com" );
		}
		#endregion
	}
}


开心洋葱 , 版权所有丨如未注明 , 均为原创丨未经授权请勿修改 , 转载请注明C#获取指定PDF文件的页数
喜欢 (0)
[开心洋葱]
分享 (0)
关于作者:
水墨上仙
……
加载中……