Crop Cairo-Generated PDF

馋奶兔 提交于 2020-02-05 01:50:30

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!