我需要从Python中打印“轮子标签”。 轮子标签将包含图像,线条和文本。
Python教程有两段关于使用图像库创建PostScript文件的段落。阅读后我仍然不知道如何布局数据。我希望有人可以提供如何布局图像,文本和线条的示例?
感谢任何帮助。
我需要从Python中打印“轮子标签”。 轮子标签将包含图像,线条和文本。
Python教程有两段关于使用图像库创建PostScript文件的段落。阅读后我仍然不知道如何布局数据。我希望有人可以提供如何布局图像,文本和线条的示例?
感谢任何帮助。
请参考http://effbot.org/imagingbook/psdraw.htm。
请注意:
PSDraw模块似乎自2005年以来没有得到积极维护;我猜测大部分的工作已经转向支持PDF格式。您可能更喜欢使用pypdf代替;
它在源代码中有像“#FIXME:不完整”和“NOT YET IMPLEMENTED”的注释;
它似乎没有任何设置页面大小的方法 - 我记得这意味着它默认为A4(8.26 x 11.69英寸);
所有的尺寸都是以点为单位,每英寸72个点。
您需要执行类似以下操作:
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。该模块本身看起来非常简单 - 他正在编写大量的原始后置脚本 - 但它应该让您更好地了解幕后发生了什么。
我建议使用开源库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()
canvas.drawImage(self, image, x,y, width=None,height=None,mask=None)
其中“image”可以是PIL图像对象,也可以是您希望使用的图像文件名。
文档中还有大量示例。