2017-10-11 57 views
0

我在以下代碼的某處收到錯誤。我有三倍檢查我的文件路徑,我相信他們是正確的。我遵循一個相當過時的教程,所以我仔細檢查了文檔,看起來是正確的。Python Reportlab pdfgen畫布無屬性

代碼:

# Import data cleaning packages. 
import csv 

# Import pdf filling packages. 
from reportlab.pdfgen import canvas 
from reportlab.lib.pagesizes import letter 
from reportlab.lib.pagesizes import landscape 
from reportlab.platypus import Image 

data_file = '/Users/josephnardone/Desktop/python/data.csv' 


def import_data(data_file): 
    attendee_data = csv.reader(open(data_file,'rb')) 
    for row in attendee_data: 
     last_name = row[0] 
     first_name = row[1] 
     pdf_file_name = last_name + '_' + first_name + '.pdf' 
     generate_certificate(first_name, last_name, pdf_file_name) 

def generate_certificate(first_name, last_name, pdf_file_name): 
    attendee_name = first_name + ' ' + last_name 
    c = canvas.Canvas(pdf_file_name, pagesize = landscape(letter)) 

    # PDF Header Text 
    c.setFont('Helvetica', 30, leading = None) 
    c.drawCenteredString(415, 500, 'Invitation to My Party') 

    c.setFont('Helvetica',15, leading = None) 
    c.drawCenteredString(415, 450, attendee_name) 

    c.showPage() 

    c.save() 

import_data(data_file) 

錯誤:

Traceback (most recent call last): 
    File "/Users/josephnardone/Desktop/python/pdf_gen.py", line 36, in <module> 
    import_data(data_file) 
    File "/Users/josephnardone/Desktop/python/pdf_gen.py", line 19, in import_data 
    generate_certificate(first_name, last_name, pdf_file_name) 
    File "/Users/josephnardone/Desktop/python/pdf_gen.py", line 27, in generate_certificate 
    c.drawCenteredString(415, 500, 'Invitation to My Party') 
AttributeError: Canvas instance has no attribute 'drawCenteredString' 
[Finished in 0.2s] 

回答

0

錯誤的教程中。問題解決了,generate_certificate的double def,請參閱下面的解決方案:

def import_data(data_file): 
    attendee_data = csv.reader(open(data_file,'rb')) 
    for row in attendee_data: 
     last_name = row[0] 
     first_name = row[1] 
     pdf_file_name = last_name + '_' + first_name + '.pdf' 

def generate_certificate(first_name, last_name, pdf_file_name): 
    attendee_name = first_name + ' ' + last_name 
    c = canvas.Canvas(pdf_file_name, pagesize = landscape(letter))