0

I've been wanting to tinker with reportlab and decided to create a virtual environment with it installed. However, when I try to run this instruction:

import reportlab
reportlab.pdfgen.canvas.Canvas("hello.pdf")

The resulting error:

PS D:\Proyectos\Generador> & "d:/Projects/Generador/generador_slips/Scripts/python.exe" "d:/Proyectos/Generador de Slips/generador.py"
Traceback (most recent call last):
  File "d:\Proyectos\Generador\generador.py", line 7, in <module>
    reportlab.pdfgen.canvas.Canvas("hello.pdf")
    ^^^^^^^^^^^^^^^^
AttributeError: module 'reportlab' has no attribute 'pdfgen'

When I ran dir(reportlab) it doesn't show the standard libraries, but only these ones:

['Version', '__builtins__', '__cached__', '__date__', '__doc__', '__file__', '__loader__', '__min_python_version__', '__name__', '__package__', '__path__', '__spec__', '__version__', '_fake_import', 'cmp', 'os', 'sys']

I've already tried uninstalling and reinstalling, force installing and even creating a new virtual environment and installing. All I've gotten is the exact same result.

Python version is 3.11.0 and reportlab version is 4.0.4

Any ideas about what can I do? Is this maybe a problem from the source repository?

MPadilla
  • 69
  • 1
  • 1
  • 7
  • Can you try `import reportlab.pdfgen` ? – Nick ODell Jun 04 '23 at 06:20
  • 1
    You can use `from reportlab.pdfgen import canvas` instead, and then `canvas.Canvas("hello.pdf")` to get the result you want. – shabnam aboulghasem Jun 04 '23 at 06:22
  • @NickODell Can run it, but cannot access the canvas or any other methods. `dir(reportlab.pdfgen)` prints out `['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__path__', '__spec__', '__version__']` – MPadilla Jun 04 '23 at 08:52
  • @shabnamaboulghasem This did work!! But why?! – MPadilla Jun 04 '23 at 08:55
  • 1
    take a look at [this](https://stackoverflow.com/questions/9303179/why-does-importing-a-python-module-not-import-nested-modules), pdfgen is a subpackage of reportlab and by importing reportlab the subpackage is not imported. – shabnam aboulghasem Jun 04 '23 at 09:54

1 Answers1

1

Try this:

from reportlab.pdfgen import canvas

canvas.Canvas("hello.pdf")

I think the module this designed in such a way we can't use it like you are trying, we have to use absolute import to use its submodule.

Divya Prakash
  • 898
  • 1
  • 6
  • 14