using Mac OS X CoreGraphics via ctypes

Daniel millerdev at gmail.com
Thu Jun 14 22:57:44 EDT 2007


I'm trying to implement a routine that converts a PDF document to
image files using ctypes and the Apple CoreGraphics library as per the
'Splitting a PDF File' example on Apple's web site [0]. Unfortunately
I cannot use the CoreGraphics module used in that example because I'm
using Python 2.5 (AFAIK that module is only available in the system
default Python 2.3.5). There are three questions in the code snippet
below. Each problem area has been commented out in the example so it
runs through to the end. The code is obviously not complete, but it's
enough do demonstrate my problems so far.

BTW, this is the only way I have found to convert a PDF (generated by
ReportLab) to an image that can be fed into a PyQt (v3) QPrinter
object. If anyone knows another way to gain access to the system print
services on Mac OS X using Python please do tell. Oh yes, I'd rather
not include PyObjC because I'm already packaging PyQt, and that would
make the resulting app a lot bigger.

# BEGIN CODE
from ctypes import cdll, c_void_p
from ctypes.util import find_library

cglib = cdll.LoadLibrary(find_library('ApplicationServices'))

# the next line causes a segfault - what's the right way to do this?
#GCS_RGB = cglib.kCGColorSpaceGenericRGB()
#cs = cglib.CGColorSpaceCreateWithName(GCS_RGB)

# the next line causes the following error:
#CGPDFDocumentRef = cglib.CGPDFDocumentRef
# AttributeError: dlsym(0x1018c0, CGPDFDocumentRef): symbol not found

CGPDFDocumentCreateWithProvider =
cglib.CGPDFDocumentCreateWithProvider
CGPDFDocumentCreateWithProvider.restype = c_void_p #CGPDFDocumentRef

provider = cglib.CGDataProviderCreateWithFilename("sample.pdf")
pdf = CGPDFDocumentCreateWithProvider(provider)

#for page in xrange(1, pdf.getNumberOfPages() + 1):
#    print page
# pdf.getNumberOfPages caues the following error:
# AttributeError: 'int' object has no attribute 'getNumberOfPages'
# I presume the 'pdf' object is a pointer. How do I get a real
# CGPDFDocuemnt instance that has a getNumberOfPages method?

cglib.CGPDFDocumentRelease(pdf)
# END CODE

[0] Splitting a PDF File <http://developer.apple.com/graphicsimaging/
pythonandquartz.html>

Thanks in advance for any hints you can provide.

~ Daniel




More information about the Python-list mailing list