Converting PDFs to Images on Mac OS X

about | archive

[ 2004-September-23 22:14 ]

I wasted a few hours writing a Mac OS X command line program to convert PDF files to PNG images at any resolution. To use it you'll have to know your way around a compiler and the command line. In Mac OS X 10.3, Preview can convert a PDF file, but it only does so at a low 72 DPI. I needed better than that, so I wrote pdf2png. Then I found PDF2Image, a Cocoa GUI that does a great job (it was mentioned in this mailing list post about NSImage sample code). Also, for developers, I have some hints about using NSImage. Update: Fixed a very minor problem with the alpha channel at the edges, because I wasn't clearing the image correctly.

To get a bitmap representation from an NSImage without resorting to the TIFFRepresentation hack (bad performance!), use the following snippet (I really should benchmark this approach against the TIFFRepresentation version):

[image lockFocus];
NSBitmapImageRep* bitmap = [ [NSBitmapImageRep alloc] initWithFocusedViewRect: destinationRect ];
[image unlockFocus];

Thanks to another mailing list post, I found that to change pages in a PDF, you have to call [source setDataRetained: YES];. Additionally, you must also call [source recache] after you called [pdfSource setCurrentPage: page].