【发布时间】:2020-10-12 11:36:09
【问题描述】:
我正在尝试将 html 文件渲染为 pdf,但是当 pdf 功能正常工作时,渲染工作正常,没有 css。它还呈现整个页面,我如何呈现 html 页面的特定部分。我正在使用 xhtml2pdf。
views.py 文件
from io import BytesIO
from django.http import HttpResponse
from django.template.loader import get_template
from django.views import View
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("utf-8")), result)
if not pdf.err:
return HttpResponse(result.getvalue(), content_type='application/pdf')
return None
data = {
"company": "Name",
}
#Opens up page as PDF
class ViewPDF(View):
def get(self, request, *args, **kwargs):
pdf = render_to_pdf('listings/listing.html', data)
return HttpResponse(pdf, content_type='application/pdf')
urls.py 文件
path('pdf_view/', views.ViewPDF.as_view(), name="pdf_view"),
html 文件
<section class="p0">
<div class="container">
<div class="row listing_single_row">
<div class="col-sm-6 col-lg-7 col-xl-8">
<div class="single_property_title">
<a href="{{ listing.photo_1.url }}" class="upload_btn popup-img"><span class="flaticon-photo-camera"></span> View Photos</a>
</div>
</div>
<div class="col-sm-6 col-lg-5 col-xl-4">
<div class="single_property_social_share">
<div class="spss style2 mt10 text-right tal-400">
<ul class="mb0">
<li class="list-inline-item"><a href="#"><span class="flaticon-transfer-1"></span></a></li>
<li class="list-inline-item"><a href="#"><span class="flaticon-heart"></span></a></li>
<li class="list-inline-item"><a href="#"><span class="flaticon-share"></span></a></li>
<li class="list-inline-item"><a href="{% url 'pdf_view' %}"><span class="flaticon-printer"></span></a></li>
</ul>
</div>
</div>
</div>
</div>
</div>
</section>
谢谢!
【问题讨论】:
-
我认为你需要在html文件中包含bootstrap css/js,因为它是一个独立的模板,与模板目录中的任何其他模板都没有关系
标签: html django django-templates