4

所以我有一个非常简单的模板,我正在使用 Wea​​syPrint 进行测试。如果将模板呈现为常规网页,它会很好地呈现。如果我尝试生成 PDF,样式就会消失。PDF 正确生成的唯一时间是当我删除引导引用时。有没有人对我引入引导 css 文件后为什么样式不起作用有任何想法?我尝试了一些 Bootstrap3 和 Bootstrap2 文件。本地和 CDN 服务。

模板:

<!doctype html>
<html lang="en">
{%  load static from staticfiles %}
{%  block head %}
    <head>
    {% block css %}
        <link rel="stylesheet" href="{%  static "css/bootstrap.min.css" %}">
        <link rel="stylesheet" href="{%  static "css/main.css" %}">
    {% endblock css %}
    </head>
{% endblock head %}
<body>
{% block content %}
    <div id="content" class="container">
        <div id="logo" class="col-md-3">
            <img src="{%  static "images/logo_small.png" %}">
        </div>
        <div id="heading" class="col-md-6">
            <h1>Packing Slip</h1>
        </div>

        <div class="col-md-3">
            <h2>{{ packslip_id }}</h2>
        </div>
    </div>
{% endblock %}
</body>
</html>

我的观点:

class WeasyPDF(TemplateView):
template_name = 'jinja2/Shipping/test_pdf.html'


def get(self, request, *args, **kwargs):
    packslip_id = kwargs.get('packslip_id')
    context= {'packslip_id': packslip_id }
    template_string = render_to_string(self.template_name, context)
    html = HTML(string=template_string, base_url=request.build_absolute_uri())
    main_doc = html.render()
    pdf = main_doc.write_pdf()
    response = HttpResponse(pdf, content_type='application/pdf')
    #Download as attachment
    # response['Content-Disposition'] = 'attachment; filename=packslip-{0}.pdf'.format(packslip_id)
    # Display in browser
    response['Content-Disposition'] = 'filename=packslip-{0}.pdf'.format(packslip_id)
    return response

最后是 urls.py 条目

    url(r'^weasypdf/(?P<packslip_id>\d+)$', WeasyPDF.as_view(), name='weasypdf'),
4

2 回答 2

0

您应该将样式表位置放在视图中,而不是模板中。

class WeasyPDF(TemplateView):
template_name = 'jinja2/Shipping/test_pdf.html'


def get(self, request, *args, **kwargs):
    packslip_id = kwargs.get('packslip_id')
    context= {'packslip_id': packslip_id }
    template_string = render_to_string(self.template_name, context)
    html = HTML(string=template_string, base_url=request.build_absolute_uri())
    main_doc = html.render()
    pdf = main_doc.write_pdf(
    stylesheets=[
        # Change this to suit your css path
        settings.BASE_DIR + 'css/bootstrap.min.css',
        settings.BASE_DIR + 'css/main.css',
    ],
    )
    response = HttpResponse(pdf, content_type='application/pdf')
    #Download as attachment
    # response['Content-Disposition'] = 'attachment; filename=packslip-{0}.pdf'.format(packslip_id)
    # Display in browser
    response['Content-Disposition'] = 'filename=packslip-{0}.pdf'.format(packslip_id)
    return response
于 2018-10-31T13:18:27.937 回答
0

我相信您需要将 CSS 呈现到您的 html 对象中: html = HTML(string=template_string, base_url=request.build_absolute_uri(), stylesheet="filename.css")

完成后,Weasyprint 会将其渲染到 HTML 对象中,以便在 PDF 和 HTML 中显示

于 2017-08-07T23:37:01.567 回答