Adi Ep
Adi Ep

Reputation: 805

django admin export to pdf

I want to export admin django to pdf (there is the normally export to csv I already have). What is the correct way to do this? There is some way in Python/Django: convert between CSV file to PDF or create a pdf file from this admin?

Upvotes: 2

Views: 2324

Answers (3)

Ibrahim Roshdy
Ibrahim Roshdy

Reputation: 21

You can accomplish this by adding a custom admin action in your ModelAdmin that redirects to your PdfCarrier view. Here’s how you can do it:

Define the admin action in your ModelAdmin:

from django.urls import reverse
from django.utils.html import format_html
from django.contrib import admin
from django.shortcuts import redirect

class CarrierAdmin(admin.ModelAdmin):
    list_display = ('name', 'export_pdf_link')

    def export_pdf(self, request, queryset):
        if queryset.count() == 1:
            carrier = queryset.first()
            return redirect(reverse('print_carrier', args=[carrier.id]))
        else:
            self.message_user(request, "Please select only one carrier.", level='error')

    export_pdf.short_description = "Export selected carrier to PDF"
    actions = [export_pdf]

    def export_pdf_link(self, obj):
        url = reverse('print_carrier', args=[obj.id])
        return format_html('<a href="{}" target="_blank">Download PDF</a>', url)

    export_pdf_link.short_description = "Export PDF"
admin.site.register(Carrier, CarrierAdmin)

This allows you to:

  • Add an “Export PDF” action in the Django Admin list view.
  • Provide a direct “Download PDF” link in the list display for each carrier.

If you want a more advanced solution with better formatting, check out my package django-pdf-actions, where I use reportlab as the PDF engine:

PYPI: https://pypi.org/project/django-pdf-actions/
GitHub: https://github.com/ibrahimroshdy/django-pdf-actions

Upvotes: 0

Ibrahim Roshdy
Ibrahim Roshdy

Reputation: 21

You can create a custom Django admin action to export data as a PDF using reportlab. Here’s a simple example:

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

def export_as_pdf(modeladmin, request, queryset):  
    response = HttpResponse(content_type='application/pdf')  
    response['Content-Disposition'] = 'attachment; filename="export.pdf"'  

    p = canvas.Canvas(response)  
    y = 800  

    for obj in queryset:  
        p.drawString(100, y, str(obj))  # Customize the output format as needed  
        y -= 20  

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

export_as_pdf.short_description = "Export selected items as PDF"  

Then, add this action to your Django admin:

class MyModelAdmin(admin.ModelAdmin):  
    actions = [export_as_pdf]  

If you want a more advanced solution with better formatting, check out my package django-pdf-actions where I use reportlab as PDF engine:

Upvotes: 0

Adi Ep
Adi Ep

Reputation: 805

 def export_audits_as_pdf(self, request, queryset):

    file_name = "audit_entries{0}.pdf".format(time.strftime("%d-%m-%Y-%H-%M-%S"))
    response = HttpResponse(content_type='application/pdf')
    response['Content-Disposition'] = 'attachment; filename="{0}"'.format(file_name)

    data = [['Action Time', 'Priority', 'username', 'Source Address', 'Subject', 'Details']]
    for d in queryset.all():
        datetime_str = str(d.action_time).split('.')[0]
        item = [datetime_str, d.priority, d.username, d.source_address, d.subject, d.details]
        data.append(item)

    doc = SimpleDocTemplate(response, pagesize=(21*inch, 29*inch))
    elements = []

    table_data = Table(data)
    table_data.setStyle(TableStyle([('ALIGN', (0, 0), (-1, -1), 'LEFT'),
                                    ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
                                    ("FONTSIZE",  (0, 0), (-1, -1), 13)]))
    elements.append(table_data)
    doc.build(elements)

    return response

Upvotes: 1

Related Questions