Page 1 of 1

Count pages of a PDF document

Posted: Tue Apr 12, 2011 9:13 pm
by Shardik
The MacOS X API contains a ton of functions to view, examine, modify and generate PDF documents. If you are interested just take a look into Apple's Quartz 2D Reference Collection. For demonstration purposes I present this short code example which simply counts the pages of a PDF document:

Code: Select all

ImportC ""
  CFRelease(CFTypeRef.L)
  CFStringCreateWithCString(CFAllocatorRef.L, CString, CFStringEncoding.L)
  CFURLCreateWithFileSystemPath(CFAllocatorRef.L, FilePath.L, PathStyle.L, IsDirectory.L)
  CGPDFDocumentCreateWithURL(CFURLRef.L)
  CGPDFDocumentGetNumberOfPages(PDFDocumentRef.L)
  CGPDFDocumentRelease(PDFDocumentRef.L)
EndImport

#kCFAllocatorDefault = 0
#kCFURLPOSIXPathStyle = 0
#kCFStringEncodingMacRoman = 0

Procedure.L OpenPDFDocument(PathAndPDFName.S)
  CFFilePath = CFStringCreateWithCString(#kCFAllocatorDefault, @PathAndPDFName, #kCFStringEncodingMacRoman)

  If CFFilePath
    CFURL = CFURLCreateWithFileSystemPath(#kCFAllocatorDefault, CFFilePath, #kCFURLPOSIXPathStyle, #False)
    
    If CFURL
      CFRelease(CFFilePath)
      PDFDocumentRef = CGPDFDocumentCreateWithURL(CFURL)
      CFRelease(CFURL)
      ProcedureReturn PDFDocumentRef
    EndIf
  EndIf

  ProcedureReturn 0
EndProcedure

Define Info.S
Define PathAndPDFName.S = "/Developer/About Xcode.pdf"

PDFDocumentRef = OpenPDFDocument(PathAndPDFName)

If PDFDocumentRef
  Info = "The PDF document '"
  Info + GetFilePart(PathAndPDFName)
  Info + "' contains " + Str(CGPDFDocumentGetNumberOfPages(PDFDocumentRef))
  Info + " pages."
  MessageRequester("PDF-Info", Info)

  CGPDFDocumentRelease(PDFDocumentRef)
EndIf