Почему Flask + ReportLab позволяет мне сделать только 1 PDF, прежде чем мне нужно перезапустить сервер?Python

Программы на Python
Ответить Пред. темаСлед. тема
Anonymous
 Почему Flask + ReportLab позволяет мне сделать только 1 PDF, прежде чем мне нужно перезапустить сервер?

Сообщение Anonymous »

Я пытаюсь сделать небольшое приложение для изготовления PDFS, и все хорошо, пока я не попытаюсь сделать второй PDF. < /p>
Вот шаги, чтобы столкнуться с проблемой: < /p>

run flask < /li>
go to 127.0.0.1:5000, Поля затем отправьте < /li>
Проверьте сгенерированный PDF (это работает!) Для первой попытки) < /li>
< /ul>
Это приложение Flask, которое я использую. Create.html - это просто форма HTML, и полученные данные будут отправлены на pdfcreater.py, чтобы генерировать < /p>
from flask import Flask, render_template, request, redirect, url_for
import pdfcreater

app = Flask(__name__)

@app.route("/", methods=["POST", "GET"])
def index():
if request.method == 'POST':
keys = request.form.keys()
data = []
temp = []

for key in keys:
temp.append(request.form[key])

for i in range(0, len(temp), 4):
data.append([temp, temp[i+1], temp[i+2], temp[i+3]])
print()
return redirect(url_for("createPdf", formData=data))
else:
return render_template("create.html")

@app.route("/")
def createPdf(formData):
pdfcreater.main(formData)

return f"{formData}"

if __name__ == '__main__':
app.run(debug=True)

< /code>
Вот pdfcreater.py:
from reportlab.pdfgen import canvas
from reportlab.lib.units import inch, cm
from reportlab.lib.pagesizes import letter
from reportlab.platypus import Spacer, SimpleDocTemplate, Table, TableStyle, Paragraph, paragraph
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle

story = [Spacer(1, 0)]

def main(data):

def my_first_page(canvas, doc):

styles = getSampleStyleSheet()
title_style = ParagraphStyle(
name='TitleStyle',
parent=styles['Title'], # Inherit from the default Title style
fontName='Helvetica-Bold', # Specify the font name
fontSize=24, # Set the font size
leading=28, # Adjust line spacing
alignment=1 # Center the title
)

centered_style = ParagraphStyle(
name='CenteredStyle',
parent=styles['Normal'], # Inherit from the default Normal style
alignment=1, # Align the text to the center
fontSize=14,
leading=16
)

customer_style = ParagraphStyle(
name='CenteredStyle',
parent=styles['Normal'], # Inherit from the default Normal style
alignment=1, # Align the text to the center
fontSize=16,
leading=20
)

left_align = ParagraphStyle(
name='reightAlignedStyle',
parent=styles['Normal'], # Inherit from the default Normal style
alignment=0, # Align the text to the right
fontSize=14,
leading=0
)

right_align = ParagraphStyle(
name='reightAlignedStyle',
parent=styles['Normal'], # Inherit from the default Normal style
alignment=2, # Align the text to the right
fontSize=14,
leading=16
)

sig_style = ParagraphStyle(
name='signature',
parent=styles['Normal'], # Inherit from the default Normal style
alignment=0, # Align the text to the right
fontSize=11,
leading=0
)

styles = getSampleStyleSheet()
blank_line = Paragraph("", title_style)
title = Paragraph("SOMETHING SOMETHING", title_style)
story.append(title)

line_of_text = Paragraph(CONFIDENTIAL", centered_style)
story.append(line_of_text)
story.append(blank_line)

date_invoice = "Date: 22/12/00"
iNum = 12345
invoice_num = f"Invoice: {iNum}"
l1 = Paragraph(date_invoice, left_align)
l2 = Paragraph(invoice_num, right_align)
story.append(l1)
story.append(l2)

customer = "customeeeeeeeeeeeeeeeeeeeeeeeeeer"
l3 = Paragraph(customer, customer_style)
story.append(l3)

invoice_data = [["gdata", "a", "b", "c"]]
invoice_data = [
['Item', 'Description', 'Description', 'Price'],
['Item 2', 'Description 2', 'Description 1', 'Price']
]
print("=================", data[0])
for item in data:
invoice_data.append(item)

while len(invoice_data) < 21:
invoice_data.append([])
# ... other items

styles = getSampleStyleSheet()
table = Table(invoice_data, colWidths=[1.25 * cm, 12.25 * cm, 2.5 *cm, 3 * cm])

n = -1
# Apply table styles (customize as needed)
table.setStyle(TableStyle([
('ALIGN', (1, 1), (-1, -1), 'LEFT'),
('TEXTCOLOR', (0, 0), (-1, 0), 'grey'),
('SPAN', (0, n), (2, n)),
('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
('INNERGRID', (0, 0), (-1, -1), 0.25, 'black'),
('BOX', (0, 0), (-1, -1), 0.25, 'black'),
]))

story.append(table)

for i in range(6):
story.append(blank_line)
sig = Paragraph("_"*24, left_align)
story.append(sig)
story.append(blank_line)
story.append(blank_line)
story.append(blank_line)
story.append(Paragraph('Signature of customer/receiving officer', sig_style))

story.append(blank_line)
story.append(blank_line)
story.append(blank_line)
story.append(blank_line)
story.append(blank_line)

story.append(sig)
story.append(blank_line)
story.append(blank_line)
story.append(blank_line)
story.append(Spacer(5 * cm, 0))
story.append(Paragraph('Name of customer/receiving officer', sig_style))
try:
print("-----------",type(eval(data)) == type([]))

if type(eval(data)) == type([]):

data = eval(data)

# fetch_data(data)
doc = SimpleDocTemplate("invoice.pdf", pagesize=letter)
# Assuming 'taaable' is your table object

doc.build(story, onFirstPage=my_first_page, onLaterPages=my_first_page)

except:
pass
< /code>
Есть идеи, почему это происходит?
заранее!>

Подробнее здесь: https://stackoverflow.com/questions/791 ... start-serv
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «Python»