问题
I have the following script which generates a number of circles in a box on top of a bigger circle. The output is to a PDF, which I would like to be tightly bounded to the ink extents.
#!/usr/bin/env python
import math
import cairocffi as cairo
import random
def DrawFilledCircle(x,y,radius,rgba):
ctx.set_source_rgba(*rgba)
ctx.arc(x,y,radius,0,2*math.pi)
ctx.fill()
def DrawCircle(x,y,radius,rgba=(0,0,0,1)):
ctx.set_source_rgba(*rgba)
ctx.arc(x,y,radius,0,2*math.pi)
ctx.stroke()
surface = cairo.RecordingSurface(cairo.CONTENT_COLOR_ALPHA, None)
ctx = cairo.Context (surface)
DrawCircle(200,200,150,(0,0,0,1))
for i in range(1000):
DrawFilledCircle(200+(150-300*random.random()), 200+(150-300*random.random()), 4, (0,0,0,0.5))
#This part will change throughout the question
extents = surface.ink_extents()
pdfout = cairo.PDFSurface ("circle.pdf", extents[2], extents[3])
pdfctx = cairo.Context (pdfout)
pdfctx.set_source_surface(surface,0,0)
Running the script produces the following.

As you can see, the width and height are correct, but the origin needs to be shifted. Accordingly, I tried this:
pdfout = cairo.PDFSurface ("circle.pdf", extents[2], extents[3])
pdfctx = cairo.Context (pdfout)
pdfctx.set_source_surface(surface,extents[0],extents[1])
This just shifted things further to the bottom right.

That suggested using negative coordinates to shift things the other way:
pdfout = cairo.PDFSurface ("circle.pdf", extents[2], extents[3])
pdfctx = cairo.Context (pdfout)
pdfctx.set_source_surface(surface,-extents[0],-extents[1])
But that didn't work either:

As a back-up, I could make a shell call to pdfcrop
, but that seems like a ridiculous workaround.
What can I do to achieve what I'm trying to do? Where am I going wrong? How can a lasting peace be achieved in Cairo?
来源:https://stackoverflow.com/questions/25066437/crop-cairo-generated-pdf