ale*_*lex 2 python pdf django reportlab
我正在使用reportlab 创建pdf。我正在使用 Reportlab 段落。问题是每次我下载它时,它都会生成一个空的txt。我在没有 django 的情况下测试了它,它工作没有问题。如果我使用画布,它可以工作,但不适合我的需要。
视图.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')
Run Code Online (Sandbox Code Playgroud)
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>
Run Code Online (Sandbox Code Playgroud)
似乎有什么问题?
您必须将文件写入流。尝试这个:
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')
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1633 次 |
| 最近记录: |