We help IT Professionals succeed at work.

Count pages in PDF documents

lee_murphy
lee_murphy used Ask the Experts™
on
Hi, I need to know how to use VBScript to get a count of PDF pages in a PDF file?

Sorry, I somehow added this to the Postgres zone for some reason...should be just VBScript.
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Top Expert 2010

Commented:
Do you have Acrobat installed?  (not just reader)

If so, you can use this:
strFilename="c:\test.pdf"
Set objAcroExch = CreateObject("AcroExch.PDDoc") 
objAcroExch.Open strFilename
CountPages = objAcroExch.GetNumPages
objAcroExch.Close

msgbox CountPages

Open in new window

Top Expert 2010

Commented:
Otherwise you could use a  wrapper for pdfinfo.exe (from XPDF)

http://gnuwin32.sourceforge.net/packages/xpdf.htm


Set WshShell = CreateObject("WScript.Shell")

strFilename="c\test2.pdf"

myCMD = "c:\xpdf-2.03-bin\bin\pdfinfo.exe " & chr(34) & strFilename & chr(34)
	
Set oExec = WshShell.Exec(myCMD)
intPages=0
While Not oExec.StdOut.AtEndOfStream
	line = oExec.StdOut.ReadLine
	If Instr(line,"Pages:") then
		intPages=CInt(split(line,":")(1))
	End If

Wend

msgbox intPages

Open in new window

Top Expert 2010
Commented:
Played around a bit using regex... turns out some other people have done this in the past.  I took a bit from here and there and modified to make my own version.

Door #3:
msgbox getNumPages("c:\test.pdf")

	
Function getNumPages(myFile)
	Set fso=CreateObject("Scripting.FileSystemObject")
	Set oFile=fso.OpenTextFile(myFile,1)
	
	While Not oFile.AtEndOfStream
		line=oFile.ReadLine
		If Instr(line,"/Count") then 
				test=0 : test=getCount(line)
				If test>0 then getNumPages=test
		End If
	Wend
	
End Function

Function getCount(myText)
	'strPattern = "/Count\s(\d{1,}).*?/Type/Pages"
	strPattern = "/Count\s(\d{1,})"
	
	Set regEx = New RegExp
	regEx.Pattern = strPattern
	
	set colMatches = regEx.Execute(myText)
	count=colMatches.count
	If count >0 then getCount = colMatches(0).submatches(0)

End Function

Open in new window