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
投稿

猜你喜欢

  • asp.net实现遍历Request的信息操作示例

    2022-11-15 23:15:18
  • Spring Boot项目维护全局json数据代码实例

    2023-04-17 23:24:10
  • Android仿微信列表滑动删除之可滑动控件(一)

    2021-12-24 21:15:46
  • 解决Spring Security中AuthenticationEntryPoint不生效相关问题

    2022-11-29 06:53:09
  • springboot web项目打jar或者war包并运行的实现

    2022-11-20 03:01:59
  • Flutter 如何封装文本输入框组件

    2023-09-27 02:54:51
  • 使用C# 的webBrowser写模拟器时的javascript脚本调用问题

    2022-03-14 23:56:31
  • SpringBoot整合Spring Data Elasticsearch的过程详解

    2023-01-25 22:39:41
  • macOS上使用gperftools定位Java内存泄漏问题及解决方案

    2023-03-02 11:42:38
  • 完美解决android M上锁屏情况下,禁止pc通过MTP访问手机存储单元

    2023-01-23 07:55:37
  • android 添加随意拖动的桌面悬浮窗口

    2023-12-27 15:57:17
  • JavaMap两种遍历方式keySet与entrySet详解

    2022-04-17 14:36:29
  • C#集合之列表的用法

    2021-12-27 19:46:43
  • Android Studio连接手机设备教程

    2021-06-10 14:40:23
  • Android Studio3.2中导出jar包的过程详解

    2021-10-14 07:06:05
  • IDEA中的.iml文件和.idea文件夹

    2023-11-23 11:47:19
  • Android如何创建桌面快捷方式

    2022-09-16 18:37:06
  • unity中点击某一个按钮播放某一个动作的操作

    2023-12-01 04:38:05
  • 实例分析java对象中浅克隆和深克隆

    2023-01-07 07:48:20
  • IDEA快速搭建spring boot项目教程(Spring initializr)

    2023-08-17 21:11:16
  • asp之家 软件编程 m.aspxhome.com