Matthias 009 Matthias 009 - 1 month ago 11
Python Question

Draw simple shapes and save to file (pdf)

I am looking for a python library that I can use to draw simple shapes and characters and then save to a file (in a format convertible to pdf). I would prefer if I did not need an X-server running.

E.g. could look something like this

import drawing_lib
obj = drawing_lib.Object()
for i in range(5):
obj.draw_line(from=(i*10, 20), to=(i*10+10, 35))
obj.save_pdf('five_inclined_lines.pdf')


Any Ideas?

Answer

You can do this with cairo.

import math,cairo

width, height = 768,768
surface = cairo.PDFSurface ("circle.pdf", width, height)
ctx = cairo.Context (surface)
ctx.set_source_rgb(1,1,1)
ctx.rectangle(0,0,width,height)
ctx.fill()
ctx.set_source_rgb(1,0,0)
ctx.move_to(width/2,height/2)
ctx.arc(width/2,height/2,512*0.25,0,math.pi*2)
ctx.fill()
ctx.show_page()

See also: