【问题标题】:Reportlab: Barcode not drawn on the top of PDF fileReportlab:条形码未绘制在 PDF 文件的顶部
【发布时间】:2017-09-05 00:46:47
【问题描述】:

我做了一些研究,但无法弄清楚。

我有以下在 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)])

【问题讨论】:

    标签: python-2.7 pdf canvas reportlab code128


    【解决方案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)
    

    【讨论】:

      猜你喜欢
      • 2023-03-05
      • 2011-07-31
      • 2017-09-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-10
      相关资源
      最近更新 更多