django 如何使用Python reportlab和BytesIO中的buffer在PDF上设置密码

huwehgph  于 2022-12-24  发布在  Go
关注(0)|答案(1)|浏览(156)

我正在尝试用Python的reportlab为生成的PDF文件添加密码,这个PDF文件是在Django的web应用程序中生成的,Django动态生成PDF文件的代码在Django的帮助页面中有详细的文档记录:

import io
from django.http import FileResponse
from reportlab.pdfgen import canvas

def some_view(request):
    # Create a file-like buffer to receive PDF data.
    buffer = io.BytesIO()

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

    # Draw things on the PDF. Here's where the PDF generation happens.
    # See the ReportLab documentation for the full list of functionality.
    p.drawString(100, 100, "Hello world.")

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

    # FileResponse sets the Content-Disposition header so that browsers
    # present the option to save the file.
    buffer.seek(0)
    return FileResponse(buffer, as_attachment=True, filename='hello.pdf')

但当我尝试向PDF文件添加密码时,生成的PDF文件是空白的。

# This results in a blank PDF document
p = canvas.Canvas(buffer, encrypt='password')

有人知道如何在reportlab中使用BytesIO缓冲区并在文件上设置密码吗?

xtfmy6hx

xtfmy6hx1#

看来你是在寻找 * 错误的方向 *。
我已经设法获得了 * 加密的PDF * 使用Django Doc本身给出的例子。在这里我发布了一个 * 更新版本 * 相同的

import io
from django.http import FileResponse
from reportlab.pdfgen import canvas

def sample_view(request):
    buffer = io.BytesIO()
    p = canvas.Canvas(buffer, encrypt="password", bottomup=False)
    p.drawString(100, 100, "This is test encryption !!!")
    p.showPage()
    p.save()
    buffer.seek(0)
    return FileResponse(buffer, as_attachment=True, filename='hello.pdf')

注解

1.我设置了bottomup=False,它允许我们以自上而下的方式编写内容(自下而上是默认行为)
1.已在Django 3.0中测试此解决方案

相关问题