我想我的HTML转换为PDF。 我看着这个教程, https://www.codingforentrepreneurs.com/blog/html-template-to-pdf-in-django/ ,我能顺利拿到教程用硬编码值工作。 问题是...我无法弄清楚如何动态地纳入我的模型和它的属性到这个例子。
下面是我遵循的步骤...
首先,我安装ReportLab的到我有以下版本环境...
pip install --pre xhtml2pdf
这个工作?
然后,我添加了一个utils.py文件到我的项目的指示。
然后我复制此代码到我的utils.py文件...
from io import BytesIO
from django.http import HttpResponse
from django.template.loader import get_template
from xhtml2pdf import pisa
def render_to_pdf(template_src, context_dict={}):
template = get_template(template_src)
html = template.render(context_dict)
result = BytesIO()
pdf = pisa.pisaDocument(BytesIO(html.encode("ISO-8859-1")), result)
if not pdf.err:
return HttpResponse(result.getvalue(), content_type='application/pdf')
return None
然后,我创建了一个HTML文件类似下面:
Titlebody {
font-weight: 200;
font-size: 14px;
}
.header {
font-size: 20px;
font-weight: 100;
text-align: center;
color: #007cae;
}
.title {
font-size: 22px;
font-weight: 100;
/* text-align: right;*/
padding: 10px 20px 0px 20px;
}
.title span {
color: #007cae;
}
.details {
padding: 10px 20px 0px 20px;
text-align: left !important;
/*margin-left: 40%;*/
}
.hrItem {
border: none;
height: 1px;
/* Set the hr color */
color: #333; /* old IE */
background-color: #fff; /* Modern Browsers */
}
Invoice #
Bill to: {{ customer_name }}
Amount: {{ amount }}
Date:
我也创造了必要的URL ....
然后,我创建了类似于下面定义的视图:
from django.http import HttpResponse
from django.views.generic import View
from yourproject.utils import render_to_pdf #created in step 4
class GeneratePdf(View):
def get(self, request, *args, **kwargs):
data = {
'today': datetime.date.today(),
'amount': 39.99,
'customer_name': 'Cooper Mann',
'order_id': 1233434,
}
pdf = render_to_pdf('pdf/invoice.html', data)
return HttpResponse(pdf, content_type='application/pdf')
当我点击我的链接这一观点上...输出显示就像教程说...
但是,如果我试图让我的模型,这个格式来显示...我难倒就如何做到这一点。 我试过的DetailView ....然后我得到的数据,但没有PDF ....我也搜索其他许多地方,似乎我无法找到一个例子,让我来动态获取我的模型和拉在属性中按需...预先感谢任何帮助或指针。