【问题标题】:Convert Remote HTML tempalte to PDF in django在 django 中将远程 HTML 模板转换为 PDF
【发布时间】:2020-11-27 04:55:34
【问题描述】:

我正在尝试将 HTML(托管在远程服务器上)转换为 pdf,然后保存在 Django 模型中。

我到目前为止所尝试的。

def convert_html_to_pdf(template, context, filename):
    response = requests.get(template)
    template = Template(response.content)

    html = template.render(Context(context))

    f = NamedTemporaryFile()
    f.name = '/' + user + '/' + str(filename)
    pdf = pisa.pisaDocument(BytesIO(template.encode('UTF-8')), f)

    if not pdf.err:
        return File(f)
    return False
file = pdf_docs.convert_html_to_pdf(
    template='https://www.example.com/sample.html',
    context={'name': 'John Smith'},
    filename='example.pdf',
)

作为响应,只有模板 URL 被打印在 PDF 上,而不是内容。

【问题讨论】:

  • 这是渲染结果html = template.render(Context(context)) 所以在这里使用pdf = pisa.pisaDocument(BytesIO(html.encode('UTF-8')), f)

标签: html python-3.x django pdf


【解决方案1】:

Javascript 有一个名为print 的函数。您可以使用 print 方法将 HTML 转换为 PDF。这是将 HTML 转换为 PDF 的代码 sn-p。另外,您可以在将 HTML 转换为 pdf 之前隐藏 JS 中的文本元素,这样您就只会打印模板。

<html>
<head>
    <title>Convert HTML to PDF</title>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script type="text/javascript">
        $("#btnPrint").live("click", function () {
            var divContents = $("#dvContainer").html();
            var printWindow = window.open('', '', 'height=400,width=800');
            printWindow.document.write('<html><head><title>DIV Contents</title>');
            printWindow.document.write('</head><body >');
            printWindow.document.write(divContents);
            printWindow.document.write('</body></html>');
            printWindow.document.close();
            printWindow.print();
        });
    </script>
</head>
<body>
    <form id="form1">
    <div id="dvContainer">
        This content needs to be printed.
    </div>
    <input type="button" value="Print Div Contents" id="btnPrint" />
    </form>
</body>
</html>

【讨论】:

    猜你喜欢
    • 2016-10-28
    • 1970-01-01
    • 1970-01-01
    • 2020-12-31
    • 2021-04-02
    • 1970-01-01
    • 2018-09-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多