让我分解一下我的要求。这就是我现在正在做的事情。
<强>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
zipPath = 'reportDir' + str(uuid.uuid4()) + '.zip'
myzip = zipfile.ZipFile(zipPath, 'w')
with myzip:
for f in lstFileNames:
myzip.write(f)
<强>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 尝试过,但结果是相同的损坏的文件
。
3. 不完全是一个问题,但我在 weasyprint 文档中找不到它。我可以强制指定文件的保存路径吗?
问题 #1 是最重要的,其余的都是次要的。我想知道我是否做得正确,即生成 pdf 文件并将其 zip 文件发送给客户端。
提前致谢。
最佳答案
稍微不同的方法是将 zip 文件移动到公共(public)目录,然后将该位置发送到客户端(例如 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 中:
var res = JSON.parse(response);
var zipFileUrl = '/' + res['zip-location'];
window.open(zipFileUrl, '_blank');
'/' + res['zip-location']
假定您的页面与 public
目录位于同一文件夹中(因此 http:///example.com/public/pdf-files-123.zip
指向文件系统上的 /var/www/public/pdf-files-123.zip
)。
您可以使用 cron 作业清理 public
目录,该作业会删除其中所有早于一小时左右的 .zip
文件。
关于javascript - 使用 Weasyprint 生成 pdf 文件,保存为 zip 文件,将该 zip 文件发送给客户端并提供下载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39772798/