【问题标题】:Printing Graphics in Python用 Python 打印图形
【发布时间】:2011-01-14 15:00:35
【问题描述】:

我需要从 python 打印“车轮标签”。车轮标签将包含图像、线条和文本。

Python 教程有两段关于使用图像库创建 postscript 文件。读完之后,我仍然不知道如何布置数据。我希望有人可能有如何布局图像、文本和线条的样本?

感谢您的帮助。

【问题讨论】:

    标签: python printing postscript


    【解决方案1】:

    http://effbot.org/imagingbook/psdraw.htm

    注意:

    1. PSDraw 模块自 2005 年以来似乎没有得到积极维护;我猜想大部分的努力已经转向支持 PDF 格式。改用 pypdf 可能会更开心;

    2. 它的源代码中包含“# FIXME:不完整”和“尚未实现”等 cmets

    3. 它似乎没有任何设置页面大小的方法 - 我记得这意味着它默认为 A4(8.26 x 11.69 英寸)

    4. 所有测量值均以磅为单位,每英寸 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 该模块本身看起来非常小——他写了很多原始的后记 - 但它应该让您更好地了解幕后发生的事情。

    【讨论】:

      【解决方案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 Image 对象,或者是您希望使用的图像的文件名。

      documentation 中也有大量示例。

      【讨论】:

        猜你喜欢
        • 2021-07-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-08-11
        • 2013-02-08
        • 1970-01-01
        • 2015-09-30
        相关资源
        最近更新 更多