作物生成PDF

2024-04-24 05:16:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我有下面的脚本,它在一个更大的圆上的一个盒子里生成了许多圆。输出是一个PDF文件,我想严格限制到墨迹范围。你知道吗

#!/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)

运行脚本会产生以下结果。你知道吗

Circle cropped in bottom right

如您所见,宽度和高度是正确的,但原点需要移动。因此,我尝试了以下方法:

pdfout  = cairo.PDFSurface ("circle.pdf", extents[2], extents[3])
pdfctx  = cairo.Context (pdfout)
pdfctx.set_source_surface(surface,extents[0],extents[1])

这只是把事情进一步转移到了右下角。你知道吗

Circle cropped even more in the bottom right

建议使用负坐标来改变事物的方向:

pdfout  = cairo.PDFSurface ("circle.pdf", extents[2], extents[3])
pdfctx  = cairo.Context (pdfout)
pdfctx.set_source_surface(surface,-extents[0],-extents[1])

但这也不管用:

Negative coordinates didn't work

作为备份,我可以对pdfcrop进行shell调用,但这似乎是一个荒谬的解决方法。你知道吗

我能做些什么来达到我想做的?我哪里出错了?如何在开罗实现持久和平?你知道吗


Tags: importsourcecontextrandommathsurfacecairoctx