我正在使用reportlab来创建pdf。我正在使用 Reportlab 段落。问题是每次我下载它时,它都会生成一个空的txt。 我在没有 django 的情况下测试了它,它工作没有问题。如果我使用 Canvas ,它可以工作,但不适合我的需要。
View .py
from django.http import HttpResponse
from django.shortcuts import render
from reportlab.lib.enums import TA_JUSTIFY
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib.pagesizes import letter
def genereaza_pdf(request):
if request.method == 'POST':
response = HttpResponse(content_type='application/pdf')
response['Content-Disposition'] = 'attachment; filename="example.pdf"'
doc = SimpleDocTemplate("example.pdf", pagesize=letter, rightMargin=70, leftMargin=70, topMargin=70,
bottomMargin=60)
report = []
styles = getSampleStyleSheet()
styles.add(ParagraphStyle(name="Times", fontName='Times-Roman', fontSize=15, alignment=TA_JUSTIFY))
p_text = "<u>ANEXA 1</u>"
report.append(Paragraph(p_text, styles["Times"]))
report.append(Spacer(1, 5))
doc.build(report)
return response
return render(request, 'pdf_test.html')
pdf_test.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Download pdf</title>
</head>
<body>
<form method="POST">
{% csrf_token %}
<button type="submit">Download</button>
</form>
</body>
</html>
问题出在哪里?
最佳答案
您必须将文件写入流。试试这个:
from io import BytesIO
def genereaza_pdf(request):
if request.method == 'POST':
response = HttpResponse(content_type='application/pdf')
response['Content-Disposition'] = 'attachment; filename="example.pdf"'
buff = BytesIO()
doc = SimpleDocTemplate(buff, pagesize=letter, rightMargin=70, leftMargin=70, topMargin=70,
bottomMargin=60)
report = []
styles = getSampleStyleSheet()
styles.add(ParagraphStyle(name="Times", fontName='Times-Roman', fontSize=15, alignment=TA_JUSTIFY))
p_text = "<u>ANEXA 1</u>"
report.append(Paragraph(p_text, styles["Times"]))
report.append(Spacer(1, 5))
doc.build(report)
response.write(buff.getvalue())
buff.close()
return response
return render(request, 'pdf_test.html')
关于python - Django Reportlab 生成空 pdf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44970128/