Hi, deepak30
The code you showed is something you can find everywhere in Web BBS, and Haluk has already presented in #4.
Searching "/Type\s*/Page[^s]" is basic.
Also this is included in my code.
But, there are cases where the function returns zero or the value grater than correct value for protected PDF.
Some protected PDF did not include the pattern "/Type\s*/Page[^s]". And/Or for some reason, it may include a number that is slightly different from the number of pages.
In that case, the return value will be 0 or a different number.
That's why I added a following pattern matches in an attempt to count on another keyword if basic pattern didn't work.
RegExp.Pattern = "/Resources"
RegExp.Pattern = "/ProcSet\s*\[/PDF"
RegExp.Pattern = "/Type/Catalog/Page\s*"
RegExp.Pattern = "/ExtGState"
Yesterday, I tried to another PDF that couldn't count with my code, I modified it. And I noticed that "Open PDF_File For Binary As #FileNum" creates a zero byte file for a non-existent file, so I added a countermeasure.
Of course, this is not perfect, and some PDFs may have slightly deviated numbers or ridiculous values.
This is a trial version.
VBA Code:
Function GetPageNum(ByVal PDF_File As String) As Long
Const NOTEXIST As Long = 0
Const UNSUPPORTNUM As Long = -99
Dim FileNum As Long
Dim strRetVal As String
Dim RegExp
Dim nFileLen As Long
Dim getpage0 As Long, getpage1 As Long, getpage2 As Long, _
getpage3 As Long, getpage4 As Long, getpage5 As Long, _
getpage6 As Long, getpage7 As Long
Application.Volatile
On Error Resume Next
nFileLen = FileLen(PDF_File)
On Error GoTo 0
If nFileLen <= 0 Then
GetPageNum = NOTEXIST
Exit Function
End If
FileNum = FreeFile
Open PDF_File For Binary As #FileNum
strRetVal = Space(LOF(FileNum))
Get #FileNum, , strRetVal
Close #FileNum
Set RegExp = CreateObject("VBscript.RegExp")
RegExp.Global = True
RegExp.Pattern = "/Type\s*/Page[^s]"
getpage0 = RegExp.Execute(strRetVal).Count
RegExp.Pattern = "/Resources"
getpage1 = RegExp.Execute(strRetVal).Count
RegExp.Pattern = "/ProcSet\s*\[/PDF"
getpage2 = RegExp.Execute(strRetVal).Count
RegExp.Pattern = "/Type/Catalog/Page\s*"
getpage3 = RegExp.Execute(strRetVal).Count
RegExp.Pattern = "/ExtGState"
getpage4 = RegExp.Execute(strRetVal).Count
RegExp.Pattern = "/Type/ObjStm"
getpage5 = RegExp.Execute(strRetVal).Count
RegExp.Pattern = "/Subtype/"
getpage6 = RegExp.Execute(strRetVal).Count
RegExp.Pattern = "<rdf:"
getpage7 = RegExp.Execute(strRetVal).Count
If getpage0 > 0 Then
GetPageNum = getpage0
Else
If getpage5 > 0 Then
If getpage7 <= 0 Then
GetPageNum = getpage6 - getpage5 - getpage4 - 1
Else
GetPageNum = UNSUPPORTNUM
End If
Else
GetPageNum = MathMax(MathMax(getpage1, getpage2), getpage3)
If GetPageNum > getpage4 Then
GetPageNum = GetPageNum - getpage4
End If
End If
End If
End Function
Function MathMax(ByVal a As Long, ByVal b As Long) As Long
If a >= b Then
MathMax = a
Else
MathMax = b
End If
End Function