将 pdf 从 django-wkhtmltopdf 保存到服务器(而不是作为响应返回) [英] Save pdf from django-wkhtmltopdf to server (instead of returning as a response)
问题描述
我正在编写一个 Django 函数,它接受一些用户输入,并为用户生成一个 pdf.然而,生成pdf的过程相当密集,我会收到很多重复的请求,所以我想将生成的pdf存储在服务器上,并在生成之前检查它们是否已经存在.
I'm writing a Django function that takes some user input, and generates a pdf for the user. However, the process for generating the pdf is quite intensive, and I'll get a lot of repeated requests so I'd like to store the generated pdfs on the server and check if they already exist before generating them.
问题是 django-wkhtmltopdf(我用于生成)旨在直接返回给用户,我不确定如何将其存储在文件中.
The problem is that django-wkhtmltopdf (which I'm using for generation) is meant to return to the user directly, and I'm not sure how to store it on the file.
我有以下内容,可用于在/pdf 处返回 pdf:
I have the following, which works for returning a pdf at /pdf:
urls.py
urlpatterns = [
url(r'^pdf$', views.createPDF.as_view(template_name='site/pdftemplate.html', filename='my_pdf.pdf'))
]
views.py
class createPDF(PDFTemplateView):
filename = 'my_pdf.pdf'
template_name = 'site/pdftemplate.html'
因此可以很好地创建 pdf.我想要的是从另一个视图调用该视图并保存结果.这是我到目前为止所得到的:
So that works fine to create a pdf. What I'd like is to call that view from another view and save the result. Here's what I've got so far:
#Create pdf
pdf = createPDF.as_view(template_name='site/pdftemplate.html', filename='my_pdf.pdf')
pdf = pdf(request).render()
pdfPath = os.path.join(settings.TEMP_DIR,'temp.pdf')
with open(pdfPath, 'w') as f:
f.write(pdf.content)
这将创建 temp.pdf 并且大约是我期望的大小,但文件无效(它呈现为一个完全空白的页面).
This creates temp.pdf and is about the size I'd expect but the file isn't valid (it renders as a single completely blank page).
有什么建议吗?
推荐答案
详细说明先前给出的答案:要生成 pdf 文件并保存到磁盘,请在您视图中的任何位置执行此操作:
Elaborating on the previous answer given: to generate a pdf file and save to disk do this anywhere in your view:
...
context = {...} # build your context
# generate response
response = PDFTemplateResponse(
request=self.request,
template=self.template_name,
filename='file.pdf',
context=context,
cmd_options={'load-error-handling': 'ignore'})
# write the rendered content to a file
with open("file.pdf", "wb") as f:
f.write(response.rendered_content)
...
我在 TemplateView 类中使用了此代码,因此 request
和 template
字段设置为这样,您可能必须将其设置为适合您特定情况的任何内容.
I have used this code in a TemplateView class so request
and template
fields were set like that, you may have to set it to whatever is appropriate in your particular case.
这篇关于将 pdf 从 django-wkhtmltopdf 保存到服务器(而不是作为响应返回)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!