Я пытаюсь создать небольшое приложение для создания PDF-файлов, и все идет хорошо, пока я не попытаюсь создать второй PDF-файл.
Вот шаги, которые помогут решить эту проблему:
Запустите приложение flask
Перейдите по адресу 127.0.0.1:5000
Заполните поля формы затем отправляются
Проверьте сгенерированный PDF-файл (он работает!)
Вернитесь в браузер, чтобы мы увидели форму и заполните ее снова< /li>
Отправить
Проверьте созданный PDF-файл (он не работает)
Перезапустите сервер flask и попробуйте выполнить описанные выше действия. еще раз (он работает, но опять же только для первой попытки)
Это приложение flask, которое я использую. create.html — это просто HTML-форма, и собранные данные будут отправлены в 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
Есть идеи, почему это происходит?
Заранее спасибо!
После поиска в Интернете я попробовал кэшировать, а также попытаться выявить узкие места. в коде, но ничего не нашел.
Я пытаюсь создать небольшое приложение для создания PDF-файлов, и все идет хорошо, пока я не попытаюсь создать второй PDF-файл. Вот шаги, которые помогут решить эту проблему: [list] [*]Запустите приложение flask [*]Перейдите по адресу 127.0.0.1:5000 [*]Заполните поля формы затем отправляются [*]Проверьте сгенерированный PDF-файл (он работает!) [*]Вернитесь в браузер, чтобы мы увидели форму и заполните ее снова< /li> Отправить [*]Проверьте созданный PDF-файл (он не работает) [*]Перезапустите сервер flask и попробуйте выполнить описанные выше действия. еще раз (он работает, но опять же только для первой попытки) [/list] Это приложение flask, которое я использую. create.html — это просто HTML-форма, и собранные данные будут отправлены в pdfCreater.py для создания [code]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[i], temp[i+1], temp[i+2], temp[i+3]]) print() return redirect(url_for("createPdf", formData=data)) else: return render_template("create.html")
[/code] Вот pdfCreater.py: [code]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 )
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))
except: pass [/code] Есть идеи, почему это происходит? Заранее спасибо! После поиска в Интернете я попробовал кэшировать, а также попытаться выявить узкие места. в коде, но ничего не нашел.