[localhost:~]$ cat * > /dev/ragfield

Tuesday, March 17, 2009

Use Quartz2D Python bindings to rasterize HTML

Since (I believe) Mac OS X 10.2, the CoreGraphics framework (Quartz2D) has included incredibly useful bindings for the Python language. This makes it very easy to test code and to automate graphics related tasks.

A few days ago a colleague asked if I knew a simple way to automate the creation of image previews of web pages. In a couple minutes I whipped up a short Python script to do just that.

import os, sys
from CoreGraphics import *

# what size image should we create?
w = 600
h = 430

# get the input and output file paths
if len(sys.argv) < 3:
	print 'usage: %s inputfile.html outputfile.png' % sys.argv[0]

input = sys.argv[1]
output = sys.argv[2]

# read the input file
f = open(input)
html = ''.join(f.readlines())

# draw the HTML into a Quartz bitmap context then write that image to a PNG file
ctx = CGBitmapContextCreateWithColor(w, h, CGColorSpaceCreateDeviceRGB(), (0, 0, 0, 0))
ctx.drawHTMLTextInRect(CGDataProviderCreateWithString(html), CGRectMake(0, 0, w, h))
ctx.writeToFile(output, kCGImageFormatPNG)

Download Python script

Unfortunately, this simple script has a fairly major limitation. It doesn't do any network access, so the HTML file and all accompanying resources must be stored somewhere on your file system.

No comments: