Reputation: 129
I did some research but couldn't figure out.
I have below code which writes barcode on a PDF file. I tried varying the width and height at this part of code, but it changes only at the bottom of the pdf file. how do i make the barcode write at the start of the PDF file?
drawon_width = 0.1*inch
drawon_height = 0.1*inch
barcode.drawOn(c, drawon_width, drawon_height)
Full code:
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)])
Upvotes: 0
Views: 1172
Reputation: 9768
From the ReportLab User Guide, we see that the arguments drawOn
are the x and y coordinates of the canvas where you want to draw the object. Additionally, in Chapter 2.1 it states:
The canvas should be thought of as a sheet of white paper with points on the sheet identified using Cartesian (X,Y) coordinates which by default have the (0,0) origin point at the lower left corner of the page.
So when you attempt to draw your barcode at 0.5*Inch, 0.5*Inch
, ReportLab attempts to draw the object half an inch from the bottom and half an inch from the left. If you'd like to draw the barcode at the top, you'll need to specify a y-value that takes into account the height of the page and the height of the bar. This code worked for me:
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)
Upvotes: 1