0

I am trying to create a "convert to pdf" button for a current page (service detail, which is a dynamic page) I tried to work with ReportLab (as Django documentation suggests, but I just can't make it work, and ReportLab documentation is not saying a word about such possibilities)

for now I can create a pdf file out of this view: (edit, got back to the code from django documentation for clarity) views.py

        @login_required
    def service_detail(request, pk):
        service = get_object_or_404(Service, pk=pk)
        return render(request, 'detail.html', {'service':service, 'pk':pk})

    @login_required
    def render_to_pdf(request):
        # Create the HttpResponse object with the appropriate PDF headers.
        response = HttpResponse(content_type='application/pdf')
        response['Content-Disposition'] = 'attachment; filename="service.pdf"''

        # Create the PDF object, using the response object as its "file."
        p = canvas.Canvas(response)

        # Draw things on the PDF. Here's where the PDF generation happens.
        p.drawString("Hello world.")

        # Close the PDF object cleanly, and we're done.
        p.showPage()
        p.save()
        return response

urls.py

url(r'^service/(?P<pk>\d+)/$', views.service_detail, name='service_detail'), #Services details
url(r'^render_to_pdf/', views.render_to_pdf, name='render_to_pdf'),

The template of the service detail includes dynamic elements, like:

Your location: {{ service.user_location }} <br><br>

Anyone knows what can I do, or what other technology I can use to create such PDF?

I am mostly working with Python, Django, HTML and CSS

1
  • 1
    "I just can't make it work" is a totally useless description of your problem. Please explain how it "doesn't work". Jun 12, 2018 at 10:43

2 Answers 2

0

content_type need to be application/pdf not service/pdf, also try to give pdf file name without spaces for example service.pdf, from docs, also you forgot to put attachment in Content-Disposition

try to write pdf to response like so and use BytesIO:

from io import BytesIO 

@login_required
def render_to_pdf(request):
    response = HttpResponse(content_type='application/pdf')
    response['Content-Disposition'] = 'inline; filename="service.pdf'
    buffer = BytesIO()
    p = canvas.Canvas(buffer)

    # Start writing the PDF here
    p.drawString(100, 100, 'Hello world.')
    # End writing

    p.showPage()
    p.save()

    pdf = buffer.getvalue()
    buffer.close()
    response.write(pdf)

    return response
3
  • Thank You for Your input! the attachment is just to make a pop-up, which I don't necessarily need. Especially that I can't get further than creating a "hello world" pdf file :( The problem is not laying there unfortunately.
    – Mai
    Jun 12, 2018 at 10:39
  • @Mai update my answer, try to use response.write(p), with BytesIO Jun 12, 2018 at 10:43
  • I still can't create a pdf out of my current page. My problem is that I can't get out of creating a "hello world". creating every single pdf manually is not an option when users create their own services with dynamic data. The code works and creates a pdf, but only pdf I can make is a random text I write into a spot of "hello world" Got through the ReportLab documentation and getting out of the ideas. Maybe another technology (not Report lab but something that just works with current dynamic page view)
    – Mai
    Jun 12, 2018 at 10:48
0

You might want to consider the package django-wkhtmltopdf for generating PDF's in Django.

Using this, you can layout your PDF as an HTML-page (with CSS markup), like any other view, but it will render it as an PDF-file. Note that you will have to install the wkhtmltopdf binary to get it working.

By adding the ?as=html prefix in the url, you can view your page in the browser while developing.

The django-wkhtmltopdf package uses class based views. Here an example:

views.py

from django.utils.text import slugify
from wkhtmltopdf.views import PDFTemplateView

class Portfolio(PDFTemplateView):
    template_name = 'frontend/portfolio.html'

    def get_filename(self):
        return slugify('portfolio ' + self.request.user.first_name + ' ' + self.request.user.last_name) + '.pdf'

    @method_decorator(login_required)
    def dispatch(self, *args, **kwargs):
        return super().dispatch(*args, **kwargs)

urls.py

from django.urls import path
from . import views

app_name = 'frontend'

urlpatterns = [
    path(
        '<slug:group_slug>/<int:school_year_pk>/portfolio/',
        views.Portfolio.as_view(),
        name='portfolio'
    ),
    ...
1
  • Thank You, I will check it out and come back if I have questions :)
    – Mai
    Jun 13, 2018 at 5:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.