我有下面的类来生成随机的简单PDF
from reportlab.pdfgen.canvas import Canvas
from reportlab.lib.pagesizes import letter
import random
import string
import os
BOOTH_NAME = [
'Distrito', 'Sector', 'Residencia', 'Fraccionamiento',
'Privado', 'Ciudad', 'Colonia', 'Departamentos',
'Recinto', 'Barrio', 'Comuna', 'Vecindad'
]
BOOTH_CODE = list(string.ascii_uppercase)
ZONE_CODE = ['NORTE', 'OESTE', 'SUR', 'ESTE', 'SUROESTE', 'NOROESTE', 'SURESTE', 'NORESTE']
CONCEPT_NAME = ['COMPRA/VENTA', 'TESTIMONIO', 'ESCRITURAS']
WIDTH, HEIGHT = letter
DIR_NAME = '/Users/gmwill934/PycharmProjects/notarIA/pdfs/'
class PDF(object):
def __init__(
self,
casilla=str(BOOTH_NAME[random.randint(0, len(BOOTH_NAME) - 1)]),
clave_casilla=str(BOOTH_CODE[random.randint(0, len(BOOTH_CODE) - 1)]),
zona=str(ZONE_CODE[random.randint(0, len(ZONE_CODE) - 1)]),
concepto=str(CONCEPT_NAME[random.randint(0, len(CONCEPT_NAME) - 1)])
):
self.casilla = casilla
self.clave_casilla = clave_casilla
self.zona = zona
self.concepto = concepto
self.name = '{} {} {}'.format(self.casilla, self.clave_casilla, self.zona)
self.save_name = os.path.join(PDF.DIR_NAME, self.name+'.pdf')
def create_pdf(self):
pdf = Canvas(self.save_name, pagesize=letter)
pdf.setTitle(self.name)
pdf.grid([10, PDF.WIDTH - 10], [10, PDF.HEIGHT - 10])
pdf.drawString(20, PDF.HEIGHT - 30, 'Numero de Casilla:')
pdf.drawString(130, PDF.HEIGHT - 30, str(random.randint(1000, 9999)))
pdf.drawString(20, PDF.HEIGHT - 50, 'Nombre de Casilla:')
pdf.drawString(130, PDF.HEIGHT - 50, self.name)
pdf.drawString(20, PDF.HEIGHT - 70, 'Numero de Votos:')
pdf.drawString(130, PDF.HEIGHT - 70, str(random.randint(100000, 999999)))
pdf.drawString(20, PDF.HEIGHT - 90, 'Concepto:')
pdf.drawString(130, PDF.HEIGHT - 90, str(self.concepto))
pdf.showPage()
pdf.save()
基本上,create_pdf方法使用随机值创建pdf
接下来我要做的是创建PDF class
的多个实例,一次创建多个PDF
from src.pdf import PDF
# instantiate PDF class
# create multiple instances
pdf = PDF()
for n in range(10):
pdf.create_pdf()
我也试过这个
from src.pdf import PDF
# instantiate PDF class
# create multiple instances
for n in range(10):
pdf = PDF()
pdf.create_pdf()
问题是,它只创建了1个PDF文件,而我预期是10个。它似乎是在1个PDF创建之后完成的
有人能对此提出建议吗?我错过什么了吗
定义函数(方法)时计算的参数的默认值
因此,您的随机生成逻辑只运行一次。
你应该做:
参考:https://docs.python.org/3/reference/compound_stmts.html#function-definitions
相关问题 更多 >
编程相关推荐