1

I was just getting started with reportlab, when I stumbled upon something. I started with some basic code:

from reportlab.lib.pagesizes import letter
from reportlab.pdfgen import canvas

def generateDoc(docName, title, codefilesFolderPath, docTextFilePath):

    canvas = canvas.Canvas(docName, pagesize=letter) 
    canvas.setLineWidth(.3)
    canvas.setFont('Helvetica', 12)
    canvas.drawString(30,750,'OFFICIAL COMMUNIQUE')
    canvas.save()

generateDoc("temp.pdf","","","")

It was giving me following error:

UnboundLocalError: local variable 'canvas' referenced before assignment

I have come to know that global variables are not freely allowed in python as in case of other languages and this post asks to use global keyword. However I am unable to get how I am supposed to do that in above code.

I tried putting import at various places, but I am not able to get how do I do this.

MsA
  • 2,599
  • 3
  • 22
  • 47
  • 2
    ...Why are you trying to overwrite the `reportlab.pdfgen.canvas` module with a `Canvas` object? I think you just need to choose better names for your variables... (i.e. names that don't clash) – Aran-Fey Aug 14 '18 at 10:48
  • aah thats what I also thought, but the code is simply copy paste from [here](https://www.blog.pythonlibrary.org/2010/03/08/a-simple-step-by-step-reportlab-tutorial/) – MsA Aug 14 '18 at 10:49
  • https://stackoverflow.com/questions/159720/what-is-the-naming-convention-in-python-for-variable-and-function-names – Amin Etesamian Aug 14 '18 at 10:50
  • Well... Now you know that you need to find a better place to copy your code from. – Aran-Fey Aug 14 '18 at 10:51

1 Answers1

0

Your local variable canvas hides the imported module canvas.

You could import Canvas directly:

from reportlab.lib.pagesizes import letter
from reportlab.pdfgen.canvas import Canvas

def generateDoc(docName, title, codefilesFolderPath, docTextFilePath):

    canvas = Canvas(docName, pagesize=letter) 
    canvas.setLineWidth(.3)
    canvas.setFont('Helvetica', 12)
    canvas.drawString(30,750,'OFFICIAL COMMUNIQUE')
    canvas.save()

generateDoc("temp.pdf","","","")
Daniel
  • 42,087
  • 4
  • 55
  • 81