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

 更新时间:2015年04月17日 15:02:53   作者:work24  
这篇文章主要介绍了C#获取指定PDF文件页数的方法,涉及C#操作pdf文件的技巧,非常具有实用价值,需要的朋友可以参考下

本文实例讲述了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# 当前系统时间获取及时间格式详解

    C# 当前系统时间获取及时间格式详解

    这篇文章主要介绍了C# 当前系统时间获取及时间格式详解的相关资料,这里提供代码实例,帮助大家学习参考,需要的朋友可以参考下
    2016-12-12
  • C#缩略图多路径多格式保存的实例

    C#缩略图多路径多格式保存的实例

    这篇文章介绍了C#缩略图多路径多格式保存的实例,有需要的朋友可以参考一下
    2013-07-07
  • C#实现简易计算器功能(2)(窗体应用)

    C#实现简易计算器功能(2)(窗体应用)

    这篇文章主要为大家详细介绍了C#实现简易计算器功能,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2022-01-01
  • C#管道式编程的介绍与实现

    C#管道式编程的介绍与实现

    这篇文章主要给大家介绍了关于C#管道式编程的介绍与实现方法,文中通过示例代码介绍的非常详细,对大家学习或者使用C#具有一定的参考学习价值,需要的朋友们下面来一起学习学习吧
    2019-07-07
  • C#编程中使用ref和out关键字来传递数组对象的用法

    C#编程中使用ref和out关键字来传递数组对象的用法

    这篇文章主要介绍了C#编程中使用ref和out关键字来传递数组对象的用法,在C#中数组也是对象可以被传递,需要的朋友可以参考下
    2016-01-01
  • c# 如何实现一个简单的json解析器

    c# 如何实现一个简单的json解析器

    这篇文章主要介绍了c# 如何实现一个简单的json解析器,文中讲解非常细致,代码帮助大家更好的理解和学习,感兴趣的朋友可以了解下
    2020-07-07
  • 深入理解C#中常见的委托

    深入理解C#中常见的委托

    本篇文章是对C#中常见的委托进行了详细的分析介绍,需要的朋友参考下
    2013-06-06
  • C# 设计模式系列教程-桥接模式

    C# 设计模式系列教程-桥接模式

    桥接模式降低了沿着两个或多个维度扩展时的复杂度,防止类的过度膨胀,解除了两个或多个维度之间的耦合,使它们沿着各自方向变化而不互相影响。
    2016-06-06
  • 利用C#/VB.NET实现将PDF转为Word

    利用C#/VB.NET实现将PDF转为Word

    众所周知,PDF 文档支持特长文件,集成度和安全可靠性都较高,可有效防止他人对 PDF 内容进行更改,所以在工作中深受大家喜爱。本文将分为两部分介绍如何以编程的方式将 PDF 转换为 Word,需要的可以参考一下
    2022-12-12
  • 如何在C#中集成Lua脚本

    如何在C#中集成Lua脚本

    这篇文章主要介绍了如何在C#中集成Lua脚本,帮助大家更好的理解和学习使用c#,感兴趣的朋友可以了解下
    2021-02-02

最新评论