首页 > 解决方案 > Django 将 HTML 渲染为 PDF

问题描述

我正在尝试将 html 文件渲染为 pdf,但是当 pdf 功能正常工作时,渲染工作正常,没有 css。它还呈现整个页面,我如何呈现 html 页面的特定部分。我正在使用 xhtml2pdf。

视图.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>

谢谢!

标签: htmldjangodjango-templates

解决方案


Ans 1.) 如果你想给你的 html 设置样式而不是直接在标签中使用 style 属性。如果您创建类并使用模板继承,那么它将无法正常工作,因为它是独立的 html。直接在html中使用样式。Ans 2.)如果您想要 pdf 中的特定 html 部分而不是在 html 中编写您需要的内容或使用 style = “display: none ;” 在您不想要的 pdf 部分上。


推荐阅读