pycairo
| Language | Python 3.10+ |
|---|---|
| License | LGPL-2.1 or MPL-1.1 |
| Repository | github.com/pygobject/pycairo |
| Documentation | surfaces reference |
| Depends on | the cairo C library (included in the Windows and macOS wheels) |
| Read / write | no / yes (EPS, Level 2 or 3) |
pycairo writes EPS through cairo.PSSurface with set_eps(True). cairo computes the %%BoundingBox from what you actually draw, so the EPS is cropped to the drawing even if the surface is larger. Fonts are embedded as subsets.
cairo can’t read EPS. Transparent drawing is converted to embedded bitmaps, because EPS has no transparency.
Installation#
Shell
pip install pycairo
Basic usage: write an EPS file#
Python
import cairo
with cairo.PSSurface("logo.eps", 200, 100) as surface: # points
surface.set_eps(True) # before drawing
surface.dsc_comment("%%Title: Logo")
ctx = cairo.Context(surface)
ctx.set_source_rgb(0.2, 0.4, 0.8)
ctx.rectangle(10, 10, 180, 80) # origin is top-left
ctx.fill()
ctx.set_source_rgb(1, 1, 1)
ctx.select_font_face("Sans", cairo.FONT_SLANT_NORMAL, cairo.FONT_WEIGHT_BOLD)
ctx.set_font_size(36)
ctx.move_to(40, 64)
ctx.show_text("LOGO")
How to put a PNG image into an EPS file#
Python
img = cairo.ImageSurface.create_from_png("photo.png")
with cairo.PSSurface("photo.eps", img.get_width(), img.get_height()) as surface:
surface.set_eps(True)
ctx = cairo.Context(surface)
ctx.set_source_surface(img, 0, 0)
ctx.paint()
How to create EPS in memory#
Python
import io
import cairo
buf = io.BytesIO()
with cairo.PSSurface(buf, 100, 100) as surface:
surface.set_eps(True)
ctx = cairo.Context(surface)
ctx.arc(50, 50, 40, 0, 6.2832)
ctx.fill()
eps_bytes = buf.getvalue() # starts with b"%!PS-Adobe-3.0 EPSF-3.0"
How to write EPS for PostScript Level 2#
Python
surface.restrict_to_level(cairo.PSLevel.LEVEL_2)
Tips#
- Draw with a function that takes a
cairo.Context, then call it with aPSSurface,PDFSurfaceandSVGSurfaceto get EPS, PDF and SVG from the same code. surface.get_eps()returns whether the surface writes EPS.