2011-01-14 84 views
5

我需要從python打印「車輪標籤」。車輪標籤將具有圖像,線條和文字。在Python中打印圖形

Python教程有兩個關於使用圖像庫創建postscript文件的段落。讀完之後,我仍然不知道如何佈置數據。我希望有人可能有如何佈置圖像,文字和線條的樣本?

感謝您的任何幫助。

回答

3

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

需要注意的是:

  1. 的PSDraw模塊不會出現已自2005年以來一直積極維護;我猜想大部分的努力都被重定向到支持PDF格式。你可能會更高興地使用pypdf來代替;

  2. 它像'#FIXME:不完整的意見和源「尚未實現」

  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模塊本身看起來非常小 - 他正在寫很多原始的postscript - 但它應該讓你更好地瞭解幕後發生的事情。

1

我會爲這類任務推薦開源庫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) 

其中「圖像」是PIL圖像對象,或者您想要使用的圖像的文件名。

documentation也有很多例子。