VB6 - Count pages in a multipage .tif file or .pdf (no dependencies).
Just a quick and dirty routine I wrote for my current project instead of paying for someone else's .dll. This is so easy to do it should be a crime to charge for it, so I thought I would post it here. Technically, there are some changes that should be made (but in practice I haven't run into a problem). There is a flag in the header that determines whether the data is big or little-endian, I haven't found a tif yet that isn't little-endian. If you need to read the flags, there is a link to the tif specification in the comments. It obviously needs error handling and input validation as well. Finally, I'm sure there is a more elegant way to build longs and ints from an array of bytes, but LSet works fine for me.
Last edited by Comintern; Nov 25th, 2007 at 04:03 PM.
Reason: Change attachment
Re: VB6 - Count pages in a multipage .tif or .pdf file (no dependencies).
Updated. Added a pdf page counter (although it may occasionally be off by a page (not sure why, probably some tag I need to exclude). Also added code to validate a correct .tif header and also use the big/little-endian flag to properly read the pointers on both file types.
Re: VB6 - Count pages in a multipage .tif file or .pdf (no dependencies).
Or use this simpler routine for PDF files:
Public Function GetNumberOfPDFPages(sFile As String) As Long
Dim lFile As Long
Dim sBuffer As String
Dim sPages() As String
Dim lStart As Long
Dim lEnd As Long
Dim lPages As Long
Dim lTotal As Long
Dim i As Long
lFile = FreeFile() 'Get file number
Open sFile For Binary As #lFile 'Open the PDF
sBuffer = String$(LOF(lFile), Chr$(0)) 'Provide buffer in the length of the file
Get #lFile, , sBuffer 'Write file to buffer
Close #lFile 'Close file
sPages = Split(sBuffer, "/Type/Pages") 'Several sections with some pages
'The first element 0 can not begin with /Type/Pages
For i = 1 To UBound(sPages)
lStart = InStr(1, sPages(i), "/Count ") 'Number of pages within a section
If lStart Then
lStart = lStart + 7 'Pointer to first digit
lEnd = lStart
Do While IsNumeric(Mid$(sPages(i), lEnd, 1))
lEnd = lEnd + 1 'Still numeric, i.e. belongs to page count
lPages = CLng(Mid$(sPages(i), lStart, lEnd - lStart))
lTotal = lTotal + lPages 'Sum up the number of pages
GetNumberOfPDFPages = lTotal