Skip to content

Instantly share code, notes, and snippets.

@SimonSapin
Created September 25, 2012 15:58
Show Gist options
  • Save SimonSapin/3782756 to your computer and use it in GitHub Desktop.
Save SimonSapin/3782756 to your computer and use it in GitHub Desktop.
WeasyPrint + PIL
from weasyprint import images as weasyprint_images
# Only monkey-patch if GDK failed to import
if not hasattr(weasyprint_images, 'PixbufLoader'):
from io import BytesIO
try:
from PIL import Image
except ImportError:
# Yeah, PIL packaging.
import Image
def pil_loader(file_obj, string):
if string is None:
# PIL wants to seek, but file_obj could be eg. a socket.
string = file_obj.read()
file_obj = BytesIO(string)
png_file = BytesIO()
Image.open(file_obj).save(png_file, 'PNG')
png_file.seek(0)
return weasyprint_images.cairo_png_loader(png_file, None)
weasyprint_images.gdkpixbuf_loader = pil_loader
@SimonSapin
Copy link
Author

This monkey-patches WeasyPrint 0.15+ to use PIL instead of GDK-pixbuf to load raster images.

Early version of GTK/GDK require a X server to run, even witouht displaying anything.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment