2017-04-10 36 views
0

我做了一些研究,但无法弄清楚。Reportlab:条形码未在PDF文件顶部绘制

我有下面的代码,在PDF文件上写条形码。我试着改变这部分代码的宽度和高度,但它只在pdf文件的底部改变。我如何在PDF文件的开始处写入条形码?

drawon_width = 0.1*inch 
drawon_height = 0.1*inch 
barcode.drawOn(c, drawon_width, drawon_height) 

全码:

import os 
import sys 

from reportlab.graphics.barcode import code128 
from reportlab.graphics.shapes import Drawing 
from reportlab.lib.pagesizes import letter 
from reportlab.lib.units import mm, inch 
from reportlab.pdfgen import canvas 
from reportlab.graphics import renderPDF 

""" 
barcode style is code128 
""" 

class BarCodeGeneration(): 

    path = os.path.dirname(os.path.abspath(__file__)) 
    files_path = os.path.join(path, 'barcode_files_generated') 

    def generate_codes(self, code_list): 
     absolute_file_path = BarCodeGeneration.files_path + 'Ahjfg7887kk' 
     c = canvas.Canvas("test.pdf") 

     for i in range(1): 
      barcode = code128.Code128("Ahjfg7887kk", barHeight=1.2*inch,barWidth = 1.6) 
      #import pdb; pdb.set_trace() 
      c.setPageSize((200*mm,80*mm)) 
      drawon_width = 0.1*inch 
      drawon_height = 0.1*inch 
      import pdb; pdb.set_trace() 
      barcode.drawOn(c, drawon_width, drawon_height, 0.1) 
      textobject = c.beginText() 
      textobject.setTextOrigin(inch, 2.5*inch) 
      lines = ["Hi", "Hello"] 
      for line in lines: 
       textobject.textLine(line) 
      c.drawText(textobject) 
      c.showPage() 
     c.save() 

obj1 = BarCodeGeneration() 
obj1.generate_codes([('Ahjfg7887kk', 3)]) 

回答

1

ReportLab User Guide,我们看到drawOn是x和画布的y坐标参数要拉拢的对象。此外,在2.1章它指出:

画布应的白纸使用笛卡尔标识在纸张上的点 一个片被认为是(X,Y)坐标,其通过 默认具有(0, 0)原点位于 页面的左下角。

因此,当您试图在0.5*Inch, 0.5*Inch处绘制条形码时,ReportLab会尝试从底部半英寸和从左半英寸处绘制对象。如果您想在顶部绘制条形码,则需要指定考虑页面高度和条形高度的y值。此代码对我有用:

bar_height = 1.2*inch 
bar_width = 1.6 
barcode = code128.Code128("Ahjfg7887kk", 
          barHeight=bar_height, barWidth=bar_width) 

page_width = 200*mm 
page_height = 80*mm 
c.setPageSize((page_width, page_height)) 
drawon_x = 0.1*inch 
drawon_y = page_height - 0.1*inch - bar_height 

barcode.drawOn(c, drawon_x, drawon_y, 0.1)