在Python中打印图形

5 投票
2 回答
9325 浏览
提问于 2025-04-16 09:57

我想用Python打印“轮子标签”。这些标签上会有图片、线条和文字。

我在Python的教程里看到有两段关于用图像库创建PostScript文件的内容。但看完之后,我还是不知道怎么把这些数据排版。我希望有人能给我一些关于如何布局图片、文字和线条的例子。

谢谢大家的帮助。

2 个回答

2

我推荐一个开源库叫做 Reportlab,非常适合这种任务。

它使用起来很简单,而且可以直接输出为PDF格式。

这是官方文档中的一个非常简单的例子:

from reportlab.pdfgen import canvas
def hello(c):
    c.drawString(100,100,"Hello World")
c = canvas.Canvas("hello.pdf")
hello(c)
c.showPage()
c.save()

只要安装了PIL,添加图片到你的页面也非常简单:

canvas.drawImage(self, image, x,y, width=None,height=None,mask=None)

这里的“image”可以是一个PIL图像对象,或者是你想使用的图片文件名。

文档中还有很多例子。

3

可以查看这个链接:http://effbot.org/imagingbook/psdraw.htm

注意以下几点:

  1. PSDrew模块自2005年以来似乎没有得到积极维护;我猜大部分精力已经转向支持PDF格式了。你可能会更喜欢使用pypdf。

  2. 源代码中有一些注释,比如'# FIXME: incomplete'和'NOT YET IMPLEMENTED'。

  3. 似乎没有设置页面大小的方法——我记得它默认是A4纸(8.26 x 11.69英寸)。

  4. 所有的测量单位都是点,72点等于1英寸。

你需要做一些类似这样的事情:

import Image
import PSDraw

# fns for measurement conversion    
PTS = lambda x:  1.00 * x    # points
INS = lambda x: 72.00 * x    # inches-to-points
CMS = lambda x: 28.35 * x    # centimeters-to-points

outputFile = 'myfilename.ps'
outputFileTitle = 'Wheel Tag 36147'

myf = open(outputFile,'w')
ps = PSDraw.PSDraw(myf)
ps.begin_document(outputFileTitle)

现在ps是一个PSDraw对象,它会把PostScript写入指定的文件,文档头已经写好——你可以开始绘制内容了。

要添加一张图片:

im = Image.open("myimage.jpg")
box = (        # bounding-box for positioning on page
    INS(1),    # left
    INS(1),    # top
    INS(3),    # right
    INS(3)     # bottom
)
dpi = 300      # desired on-page resolution
ps.image(box, im, dpi)

要添加文本:

ps.setfont("Helvetica", PTS(12))  # PostScript fonts only -
                                  # must be one which your printer has available
loc = (        # where to put the text?
    INS(1),    # horizontal value - I do not know whether it is left- or middle-aligned
    INS(3.25)  # vertical value   - I do not know whether it is top- or bottom-aligned
)
ps.text(loc, "Here is some text")

要添加一条线:

lineFrom = ( INS(4), INS(1) )
lineTo   = ( INS(4), INS(9) )
ps.line( lineFrom, lineTo )

... 但我没有看到任何选项来改变线条粗细。

完成后,你需要像这样关闭文件:

ps.end_document()
myf.close()

补充:我查了一下关于设置线条粗细的内容,发现了一个不同的模块,叫做psfile:http://seehuhn.de/pages/psfile#sec:2.0.0。这个模块看起来很简单——他写了很多原始的PostScript代码——但它应该能让你更好地理解背后的工作原理。

撰写回答