C#获取指定PDF文件页数的方法
本文实例讲述了C#获取指定PDF文件页数的方法。分享给大家供大家参考。具体如下:
usingSystem;
usingSystem.IO;
usingSystem.Text.RegularExpressions;
usingSystem.Windows.Forms;
namespaceRobvanderWoude
{
classPDFPageCount
{
staticintMain(string[]args)
{
#regionGethelp
if(args.Length==0)
{
ShowHelp();
return0;
}
foreach(stringarginargs)
{
if(arg=="/?"||arg=="-?"||arg.ToLower()=="--help")
{
ShowHelp();
return0;
}
}
#endregion
interrors=0;
foreach(stringarginargs)
{
try
{
Regexregexp=newRegex(@"^(.*)\\([^\\]+\.pdf)$",RegexOptions.IgnoreCase);
if(regexp.IsMatch(arg))
{
//Matchmeansthefilespechasavalidformat(i.e.*.pdf)
string[]matches=regexp.Split(arg);
stringfolder=matches[1];
stringfilespec=matches[2];
if(Directory.Exists(folder))
{
//Folderexists,checkformatchingfiles
string[]fileList=Directory.GetFiles(folder,filespec);
if(fileList.Length==0)
{
//Nomatchingfilesinthisfolder
ShowError("ERROR:Nofilesmatching\"{0}\"werefoundin\"{1}\"",filespec,folder);
errors+=1;
}
else
{
//Iteratethroughlistofmatchingfiles
foreach(stringfileinfileList)
{
intpagecount=PageCount(file);
if(pagecount==-1)
{
//Justincreasetheerrorcount,thePageCount()
//procedurealreadywroteanerrormessagetoscreen
errors+=1;
}
else
{
//Nopagesmeansthereisaproblemwiththefile
if(pagecount==0)
{
Console.ForegroundColor=ConsoleColor.Red;
errors+=1;
}
//Displaytheformatedresultonscreen
Console.WriteLine("{0,4}{1,-10}{2}",pagecount.ToString(),(pagecount==1?"page":"pages"),file);
if(pagecount==0)
{
Console.ForegroundColor=ConsoleColor.Gray;
}
}
}
}
}
else
{
//Folderdoesn'texist
ShowError("ERROR:Folder\"{0}\"notfound",folder);
errors+=1;
}
}
else
{
//Nomatchfortheregularexpressionmeansthefilespecwasinvalid
ShowError("ERROR:Invalidfilespec\"{0}\",pleasespecifyPDFfilesonly",arg);
errors+=1;
}
}
catch(Exceptione)
{
//Allothererrors:displayanerrormessageandthencontinue
ShowError("ERROR:{0}",e.Message);
errors+=1;
}
}
if(errors!=0)
{
ShowError("{0}finishedwith{1}error{2}",GetExeName(),errors.ToString(),(errors==1?"":"s"));
}
returnerrors;
}
staticstringGetExeName()
{
stringexe=Application.ExecutablePath.ToString();
Regexregexp=newRegex(@"\\([^\\]+)$");
returnregexp.Split(exe)[1];
}
staticintPageCount(stringfilename)
{
Regexregexp=newRegex(@"\.pdf$",RegexOptions.IgnoreCase);
if(regexp.IsMatch(filename))
{
try
{
FileStreamfs=newFileStream(filename,FileMode.Open,FileAccess.Read);
StreamReadersr=newStreamReader(fs);
stringpdfText=sr.ReadToEnd();
regexp=newRegex(@"/Type\s*/Page[^s]");
MatchCollectionmatches=regexp.Matches(pdfText);
returnmatches.Count;
}
catch(Exceptione)
{
ShowError("ERROR:{0}({1})",e.Message,filename);
return-1;
}
}
else
{
ShowError("ERROR:{0}isnotaPDFfile",filename);
return-1;
}
}
staticvoidShowError(stringmessage,stringparam1,stringparam2="",stringparam3="")
{
Console.Error.WriteLine();
Console.ForegroundColor=ConsoleColor.Red;
Console.Error.WriteLine(message,param1,param2,param3);
Console.ForegroundColor=ConsoleColor.Gray;
Console.Error.WriteLine();
}
#regionDisplayhelptext
staticvoidShowHelp()
{
Console.Error.WriteLine();
Console.Error.WriteLine("{0},Version1.02",GetExeName());
Console.Error.WriteLine("ReturnthepagecountforthespecifiedPDFfile(s)");
Console.Error.WriteLine();
Console.Error.WriteLine("Usage:{0}filespec[filespec[filespec[...]]]",GetExeName().ToUpper());
Console.Error.WriteLine();
Console.Error.WriteLine("Where:\"filespec\"isafilespecificationforthePDFfile(s)to");
Console.Error.WriteLine("belisted(wildcards*and?areallowed)");
Console.Error.WriteLine();
Console.Error.WriteLine("Note:Theprogram'sreturncodeequalsthenumberoferrorsencountered.");
Console.Error.WriteLine();
Console.Error.WriteLine("WrittenbyRobvanderWoude");
}
#endregion
}
}
希望本文所述对大家的C#程序设计有所帮助。