使用Weasyprint生成PDF文件,保存在压缩文件中,发送压缩文件给客户并提供下载

2024-05-19 11:03:13 发布

您现在位置:Python中文网/ 问答频道 /正文

让我把我的要求分解一下。这就是我现在正在做的。在

1。从HTML生成PDF文件

为此,我使用Weasyprint如下:

lstFileNames = []
for i, content in enumerate(lstHtmlContent):
    repName = 'report'+ str(uuid.uuid4()) + '.pdf'
    lstFileNames.append("D:/Python/Workspace/" + repName)

    HTML(string=content).write_pdf(target=repName,
        stylesheets=[CSS(filename='/css/bootstrap.css')])

所有文件名和路径都保存在lstFileNames中。在

2。使用weasyprint生成的pdf文件创建zip文件

我用的是zipfile

^{pr2}$

3。将zip文件发送到客户端进行下载

resp = HttpResponse(myzip, content_type = "application/x-zip-compressed")

resp['Content-Disposition'] = 'attachment; filename=%s' % 'myzip.zip'

4。打开文件通过Javascript下载

var file = new Blob([response], {type: 'application/x-zip-compressed'});
var fileURL = URL.createObjectURL(file);
window.open(fileURL);

问题

1。当前端成功接收到zip文件时,当我尝试打开它时,会出现以下错误:

The archive is in either unknown format or damaged

我发送的文件是错的还是我的Javascript代码有问题?在

2.是否有一种方法可以将所有pdf文件存储在字节数组列表中,并使用这些字节数组生成zip文件并将其发送给客户端?我用weasyprint尝试过,但结果是一样的damaged file。在

3.不完全是个问题,但我在weasyprint文档中找不到。我可以强制文件保存的路径吗?在

问题1是最重要的,其余的是次要的。我想知道我做的是否正确,即生成pdf文件并将其zip文件发送给客户。在

提前谢谢。在


Tags: 文件in路径客户端pdfhtmlcontentzip
2条回答

退出with块后,文件句柄将关闭。您应该重新打开文件(这次使用open)并使用read()将内容传递给HttpResponse,而不是传递filehandle本身。在

with zipfile.ZipFile(zipPath, 'w') as myzip
    for f in lstFileNames:
        myzip.write(f)
with open(zipPath, 'r') as myzip:
    return HttpResponse(myzip.read(), content_type = "application/x-zip-compressed")

如果可以,那么可以使用StringIO实例而不是filehandle来存储zip文件。我不熟悉Weasyprint,所以我不知道您是否可以使用StringIO来实现这一点。在

一种稍有不同的方法是将zip文件移动到公共目录,然后将该位置发送到客户端(例如json格式),即:

publicPath = os.path.join('public/', os.path.basename(zipPath))
os.rename(zipPath, os.path.join('/var/www/', publicPath))

jsonResp = '{ "zip-location": "' + publicPath + '" }'

resp = HttpResponse(jsonResp, content_type = 'application/json');

然后在客户端的javascript中:

^{pr2}$

'/' + res['zip-location']假设页面与public目录位于同一个文件夹中(因此http://example.com/public/pdf-files-123.zip指向文件系统上的/var/www/public/pdf-files-123.zip)。在

您可以使用cron作业清理public目录,该作业将删除其中超过一小时的所有.zip文件。在

相关问题 更多 >

    热门问题