Search code examples
pythondjangopdfreportlab

Django Reportlab generates empty pdf


I'm using reportlab to create a pdf. I am using Reportlab Paragraphs. The problem is everytime i download it, it generates an empty txt. I tested it without django and it works without a problem. If i'm using canvas it works but it doesn't suit what i need.

views.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>

What seems to be the problem?


Solution

  • The function was generating two files, one in Downloads as default but it was an empty txt and one in the project's directory. I've made the changes.

    def genereaza_pdf(request):
        if request.method == 'POST':
            response = HttpResponse(content_type='application/pdf')
            response['Content-Disposition'] = 'attachment; filename="example.pdf"'
            doc = SimpleDocTemplate(response, 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')