为什么我看到“IndexError:字符串索引超出范围”

时间:2014-02-12 00:23:49

标签: python pdf-generation

我正在尝试使用reportlab的pdfgen来绘制PDF,但是当我尝试保存我的画布时,我得到了一个很大的错误:

---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
/usr/local/bin/ipython-listener in <module>()
----> 1 c = set_canvas(); c.save()

/usr/lib/python2.7/dist-packages/reportlab/pdfgen/canvas.pyc in save(self)
   1191            If there is current data a ShowPage is executed automatically.
   1192            After this operation the canvas must not be used further."""
-> 1193         if len(self._code): self.showPage()
   1194         self._doc.SaveToFile(self._filename, self)
   1195 

/usr/lib/python2.7/dist-packages/reportlab/pdfgen/canvas.pyc in showPage(self)
    582 
    583         pageWidth = self._pagesize[0]
--> 584         pageHeight = self._pagesize[1]
    585         cM = self._cropMarks
    586         code = self._code

IndexError: string index out of range

这是相关代码:

from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import landscape, letter
from reportlab.lib.units import inch

def set_canvas():
    c = canvas.Canvas("bingo.pdf")
    c.setPageSize(letter)
    c.setPageRotation(90)
    c.setFont('Helvetica-Bold', 14)
    return c

一旦加载,我就会运行c = set_canvas()c.save()并收到错误。如果我注释掉setPageSize行似乎有效:

def set_canvas():
    c = canvas.Canvas("bingo.pdf")
    c.setPageRotation(90)
    c.setFont('Helvetica-Bold', 14)
    return c

c = set_canvas()    
c.drawString(72, 72, "Why is this so hard?")
c.save()

但是当我添加字体大小时,我才开始遇到这个问题。我无法弄清楚我在这里缺少什么。

1 个答案:

答案 0 :(得分:0)

from reportlab.lib.pagesizes import landscape, letterletter设置为元组(612.0, 792.0) - 但我后来在我的脚本中使用“letter”作为变量,有效地将其重新定义为字符串。并且字符串没有索引[1]因此当reportlab尝试使用pageHeight = self._pagesize[1]

设置pageHeight时它超出范围

不是没有,运行pylint会让我更快地解决问题。