C#获取指定PDF文件页数的方法
作者:work24 发布时间:2021-10-10 17:15:43
标签: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#程序设计有所帮助。


猜你喜欢
- 一、Lombok从上一篇博客可看出,DAO接口类的编写变得简单,反过来看模型,编写还需要(私有属性、setter...getter...方法
- Eclipse Che被Eclipse官方称为下一代IDE,作为老牌的IDE,被其寄予厚望的Eclipse Che到底有什么特点,在这篇文章
- 做个网站的安卓客户端,用户安装到自己手机上,如果我出了新版本怎么办呢?要有版本更新功能。 本来版本检测最好可以自动进行。但如果每次开启程序,
- 1、引入依赖<dependency> <groupId>org.apache.pdfbox</gr
- 以一个M×N的长方阵表示迷宫,0和1分别表示迷宫中的通路和障碍。设计一个程序,对任意设定的迷宫,求出一条从入口到出口的通路,或得出没有通路的
- 前言在应用启动的时候,为了加快启动速度,往往需要把一些比较重的操作放到子线程中,或者是延时加载。将任务放在子线程中是一个比较简单并且看起来有
- 看到正点闹钟上的设置时间的滑动效果非常好看,自己就想做一个那样的,在网上就开始搜资料了,看到网上有的齿轮效果的代码非常多,也非常难懂,我就决
- 完整代码已上传到GitHub。Web端体验地址:http://47.116.72.33/(只剩一个月有效期)apk下载地址:https://
- 前言反射是我们框架的灵魂,反射也是我们框架的一个底层基石,没有反射也就没有框架,如果我们学好了反射,对我们阅读框架底层是有很大班助的——阿俊
- 一、maven引入依赖,数据库驱动根据项目需求自行引入<!-- https://mvnrepository.com/artifact/
- Feign获取异常信息最近在使用Feign调用时,出现了异常,原本使用的是fallback,直接返回了自定义的结果@Override &nb
- ReentrantLock锁ReentrantLock是Java中常用的锁,属于乐观锁类型,多线程并 * 况下。能保证共享数据安全性,线程间有
- SpringMVC配置多个properties文件之通配符在springmvc中配置加载properties文件一般会在xml文件中配置如下
- instanceof关键字用于判断一个引用类型变量所指向的对象是否是一个类(或接口、抽象类、父类)的实例。 举个例子:public
- 栈和队列:都是线性表,都是基于List基础上的实现线性表:数组,链表,字符串,栈,队列元素按照一条“直线&rdq
- 用C#如何生成二维码,我们可以通过现有的第三方dll直接来实现,下面列出几种不同的生成方法:1):通过QrCodeNet(Gma.QrCod
- SpringMVC通过模型视图ModelAndView渲染视图大致流程代码样例1.准备工作A.因为文中用到jsp,所以需要引入jsp标准标签
- java调用外部程序的方法 在一个java应用中,可能会遇到这样的需求,就是需要调用一些外部的应用做一些处理,比如调用excel,
- 前言Feign是Netflix开源的声明式HTTP客户端,致力于让编写http client更加简单,Feign可以通过声明接口自动构造请求
- 序言使用SpringBoot创建定时任务非常简单,目前主要有以下三种创建方式:一、基于注解(@Scheduled)二、基于接口(Schedu