#regionGet the number of pages in a PDF filePrivate intByteslastindexof (byte[] buffer,intLengthstringSearch) { if(Buffer = =NULL) return-1; if(buffer. Length <=0) return-1; byte[] Searchbytes =Encoding.Default.GetBytes (Search.toupper ()); for(inti = length-searchbytes.length; I >=0; i--) { BOOLBfound =true; for(intj =0; J < Searchbytes.length; J + +) { if(Byteupper (Buffer[i + j])! =Searchbytes[j]) {Bfound=false; Break; } } if(Bfound)returni; } return-1; } Private byteByteupper (bytebytevalue) { CharCharvalue =Convert.tochar (Bytevalue); if(Charvalue <'a'|| Charvalue >'Z') returnBytevalue; Else returnConvert.tobyte (Bytevalue- +); } /// <summary> ///get the number of pages in a PDF file/// </summary> Public intGetpdfpagecount (stringPath//get the number of pages in a PDF file{Path=HttpContext.Current.Server.MapPath (path); byte[] buffer =file.readallbytes (path); intLength =buffer. Length; if(Buffer = =NULL) return-1; if(buffer. Length <=0) return-1; Try { //Sample//0 obj//<</count 9//type/pages inti =0; intNPos = byteslastindexof (buffer, length,"/type/pages"); if(NPos = =-1) return-1; stringPageCount =NULL; for(i = nPos; i < length-Ten; i++) { if(Buffer[i] = ='/'&& Buffer[i +1] =='C'&& Buffer[i +2] =='o'&& Buffer[i +3] =='u'&& Buffer[i +4] =='N'&& Buffer[i +5] =='T') { intj = i +3; while(Buffer[j]! ='/'&& Buffer[j]! ='>') J++; PageCount= Encoding.Default.GetString (buffer, I, J-i); Break; } } if(PageCount = =NULL) return-1; intn = pagecount.indexof ("Count"); if(N >0) {PageCount= pagecount.substring (n +5). Trim (); for(i = pagecount.length-1; I >=0; i--) { if(Pagecount[i] >='0'&& Pagecount[i] <='9') { return int. Parse (Pagecount.substring (0, i +1)); } } } return-1; } Catch(Exception ex) {return-1; } } #endregion
Dotnet get the number of pages in a PDF file