我今天已经玩ReportLab的和Django的一整天,我终于有了它的这个问题SO帮助今天早些时候... https://stackoverflow.com/questions/54565679/how-to-incorporate-reportlab-with-django-class-based-view/54566002#=输出如预期的那样,现在正在制作的PDF工作。然而,我不能得到的图像,当输出被生产为PDF来显示。没有渲染。
我曾试图调查我的网址,我绝对URL在我的settings.py文件并没有什么。我发现我不能让我的模板拿起我的任何静态设置,但我的项目的其余工作正常使用相同的引用。我也发现了这个非常相似的,所以问题,但似乎无法确定实际修复.... html template to pdf with images
我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模板文件...
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Title</title>
<style type="text/css">
body {
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 */
}
</style>
</head>
<body>
<img class="logo3" src="/book/author.svg" >
<div class='wrapper'>
<div class='header'>
<p class='title'>Invoice # </p>
</div>
<div>
<div class='details'>
Bill to: {{ customer_name }} <br/>
Amount: {{ amount }} <br/>
Date:
<hr class='hrItem' />
</div>
</div>
</body>
</html>
和视图....
class SomeDetailView(DetailView):
model = YourModel
template_name = 'pdf/invoice.html'
def get_context_data(self, **kwargs):
context = super(SomeDetailView, self).get_context_data(**kwargs)
# add extra context if needed
return context
def render_to_response(self, context, **kwargs):
pdf = render_to_pdf(self.template_name, context)
return HttpResponse(pdf, content_type='application/pdf')
我试图让author.svg形象出现在PDF,但没有运气的呢。
一堆的反复试验后我放弃了对SVG的做法现在...,而是选择使用PNG文件。我发现这一点,以便给我的回答...如下图所示django - pisa : adding images to PDF output是作为参考在通过Django模板我的模型的属性一样简单:
包括我在我的模型中的默认位置。我尝试用一个PNG和SVG。巴新的工作,但在SVG没有。无论哪种方式,这解决了我的问题。