The Shape of Everything
A website mostly about Mac stuff, written by August "Gus" Mueller
» Acorn
» Retrobatch
» Mastodon
» Micro.blog
» Instagram
» Github
» Maybe Pizza?
» Archives
» Feed
» Micro feed
October 4, 2004
(This post is from my old, old, super old site. My views have changed over the years, hopefully my writing has improved, and there is now more than a handful of folks reading my site. Enjoy.)

Monday, October 4th, 2004

Here's a quick little osx python script that can be used to convert a pdf to a png, remembering alpha channels and such. I needed one real quick, so I figure someone else might need it someday as well.

#!/usr/bin/python from CoreGraphics import * import sys, os

if len(sys.argv) < 2:     print "usage: %s pdffile.pdf [ outfile.png ]" % sys.argv[0]     sys.exit (1)

in_file = sys.argv[1]

out_file = in_file + ".png"

if len(sys.argv) == 3:     out_file = sys.argv[2]

read in our pdf.

pdf = CGPDFDocumentCreateWithProvider(         CGDataProviderCreateWithFilename(in_file)      )

find it's bounds.

r = pdf.getMediaBox(1)

create a context to draw to

ctx = CGBitmapContextCreateWithColor(          r.size.width, r.size.height,          CGColorSpaceCreateWithName (kCGColorSpaceUserRGB),          (0, 0, 0, 0, 1)         )

#draw the pdf to the context ctx.drawPDFDocument(r, pdf, 1)

write out the bitmap to a file as png.

ctx.writeToFile(out_file, kCGImageFormatPNG)

-- posted 12:16 am