pythonpdfreportlab

Python Reportlab units, cm and inch, are translated differently


If I draw two PDF files with ReportLab (vers. 3.2.0) with either cm or inch settings I get two different PDFs.

I have two functions that to me look exactly equal. In one I place the text into position (5.0*inch, 10.0*inch) and in the other I place them in (5.0*2.54*cm, 10.0*2.54*cm). Obviously, I use 2.54 to translate the lengths from inches to centimeters.

The problem is that the text gets placed in different positions. Am I missing something, is this a bug or what's going on?

Below I have added the code that replicates my problem as well as pictures of the two outcomes.

from reportlab.pdfgen import canvas
from reportlab.lib.units import inch, cm
from reportlab.lib.pagesizes import A4

def cm_test():
    c = canvas.Canvas("inch.pdf", pagesize=A4)
    c.translate(inch, inch)
    text_object = c.beginText(5.0*inch, 10.0*inch)
    text_object.textLine("INCH: text located here")
    c.drawText(text_object)
    c.save()

def inch_test():
    c = canvas.Canvas("cm.pdf", pagesize=A4)
    c.translate(cm, cm)
    text_object = c.beginText(5.0*2.54*cm, 10.0*2.54*cm)
    text_object.textLine("CM: text located here")
    c.drawText(text_object)
    c.save()

if __name__ == "__main__":
    cm_test()
    inch_test()

Pic 1: Outcome of function cm_test()

Pic 2: Outcome of function inch_test()


Solution

  • This is not the bug, the reason the text is printed at different places as the following lines:

    c.translate(inch, inch)
    c.translate(cm, cm)
    

    These statements move the canvas origin 1 cm/inch up and right. As Reportlab draws based on this origin the text is placed at different position.