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

作者:work24 时间:2021-10-10 17:15:43 

本文实例讲述了C#获取指定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 )
 {
  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" );
 }
 #endregion
}
}

希望本文所述对大家的C#程序设计有所帮助。

标签:C#,PDF
0
投稿

猜你喜欢

  • springboot使用mybatis一对多的关联查询问题记录

    2023-05-25 14:31:03
  • java实现基于Tcp的socket聊天程序

    2022-03-11 15:28:07
  • SpringBoot2.0 ZipKin示例代码

    2022-11-25 00:24:40
  • Java Swing程序设计实战

    2023-04-09 07:05:42
  • Java多线程synchronized同步方法详解

    2023-06-30 00:39:42
  • Java7到Java17之Switch语句进化史示例详解

    2021-11-03 18:47:37
  • C++高并发内存池的整体设计和实现思路

    2023-07-03 16:29:31
  • 详解Java如何进行Base64的编码(Encode)与解码(Decode)

    2023-01-31 18:53:34
  • 深入了解Java虚拟机栈以及内存模型

    2022-02-17 13:37:50
  • 关于Android 6.0权限的动态适配详解

    2021-09-16 07:56:34
  • 解决Unity无限滚动复用列表的问题

    2022-12-26 04:42:18
  • Java 实战项目锤炼之医院门诊收费管理系统的实现流程

    2022-08-10 11:35:08
  • C++实现经典24点纸牌益智游戏

    2023-04-22 01:05:02
  • Java集合ArrayDeque类实例分析

    2022-06-19 18:25:06
  • Java接口返回省市区树形结构的实现

    2021-10-16 05:07:05
  • springboot 跨域配置类及跨域请求配置

    2023-01-31 14:27:19
  • Spring源码之循环依赖之三级缓存详解

    2021-11-13 09:31:56
  • Java日常练习题,每天进步一点点(58)

    2021-06-26 01:13:02
  • android实现横屏的代码及思路

    2023-06-25 09:35:40
  • java中的Object类的toSpring()方法

    2022-08-30 12:36:03
  • asp之家 软件编程 m.aspxhome.com