31

I'm working in a site using Django and I print a .pdf file using Repotlab.

Now, I want the file to have multiple pages, how can I do it?

My code:

from reportlab.pdfgen import canvas
from django.http import HttpResponse

def Print_PDF(request):
    response = HttpResponse(content_type='application/pdf')
    response['Content-Disposition'] = 'attachment; filename="resume.pdf"'

    p = canvas.Canvas(response)

    p.drawString(100, 100, "Some text in first page.")
    p.drawString(200, 100, "Some text in second page.")
    p.drawString(300, 100, "Some text in third page")

    p.showPage()
    p.save()
    return response

Thanks in advance.

Andres
  • 4,323
  • 7
  • 39
  • 53

1 Answers1

66

showPage(), despite its confusing name, will actually end the current page, so anything you draw on the canvas after calling it will go on the next page.

In your example, you can just use p.showPage() after each p.drawString example and they will all appear on their own page.

def Print_PDF(request):
    response = HttpResponse(content_type='application/pdf')
    response['Content-Disposition'] = 'attachment; filename="resume.pdf"'

    p = canvas.Canvas(response)

    p.drawString(100, 100, "Some text in first page.")
    p.showPage()

    p.drawString(200, 100, "Some text in second page.")
    p.showPage()

    p.drawString(300, 100, "Some text in third page")
    p.showPage()

    p.save()
    return response
Nitzle
  • 2,417
  • 2
  • 22
  • 23
  • 4
    I already got it, but I couldn't answer for my reputation. Your answer is **perfect**, thanks a lot. – Andres Sep 06 '13 at 21:17
  • 2
    Thank you for the simple and clear explanation and example. – David Maness Apr 12 '19 at 15:52
  • When I use the drawString method the text is displayed in the next pages, but nothing happens if I create a new PDFTextObject and draw lines ... – Jonathan Sep 20 '21 at 10:11