Home > Enterprise >  pdfencrypt with Reportlab
pdfencrypt with Reportlab

Time:11-28

I want to add password protection for opening the pdf file from a Django project.

def pdf_view(request):
    response = HttpResponse(content_type='application/pdf')
    response['Content-Disposition'] = 'attachment; filename="members.pdf"'
    elements = []
    doc = SimpleDocTemplate(response, rightMargin=0.5 * cm, leftMargin=6.5 * cm, topMargin=0.3 * cm, bottomMargin=0)
    rows = []
    users = User.objects.all()
    for user in users:
        rows.append((
            user.username,
            user.email,
            user.first_name,
            user.last_name,
            formats.date_format(user.date_joined, "SHORT_DATETIME_FORMAT"),
            formats.date_format(user.subscriptions.current_period_end, "SHORT_DATETIME_FORMAT")
        ))
    table = Table(rows, colWidths=46 * mm, rowHeights=30, repeatRows=1)
    table.setStyle([
        ('GRID', (0, 0), (-1, -1), 0.25, colors.black),
        ("ALIGN", (0, 0), (-1, -1), "LEFT"),
    ])
    table = Table(rows, colWidths=46 * mm, rowHeights=30, repeatRows=1)
    elements.append(table)
    doc.build(elements)
    return response

where can I add this line of code to do encryption

pdfencrypt.StandardEncryption("password", canPrint=0)

any help will be much appreciated

CodePudding user response:

you can add the line of code as below

def pdf_view(request):
    response = HttpResponse(content_type='application/pdf')
    response['Content-Disposition'] = 'attachment; filename="members.pdf"'
    elements = []
    **doc = SimpleDocTemplate(response, encrypt=pdfencrypt.StandardEncryption("pass", canPrint=0)**, rightMargin=0.5 * cm, leftMargin=6.5 * cm, topMargin=0.3 * cm, bottomMargin=0)
    rows = []
    users = User.objects.all()
    for user in users:
        rows.append((
            user.username,
            user.email,
            user.first_name,
            user.last_name,
            formats.date_format(user.date_joined, "SHORT_DATETIME_FORMAT"),
            formats.date_format(user.subscriptions.current_period_end, "SHORT_DATETIME_FORMAT")
        ))
    table = Table(rows, colWidths=46 * mm, rowHeights=30, repeatRows=1)
    table.setStyle([
        ('GRID', (0, 0), (-1, -1), 0.25, colors.black),
        ("ALIGN", (0, 0), (-1, -1), "LEFT"),
    ])
    table = Table(rows, colWidths=46 * mm, rowHeights=30, repeatRows=1)
    elements.append(table)
    doc.build(elements)
    return response
  • Related