首页 > 解决方案 > 在 django 中将远程 HTML 模板转换为 PDF

问题描述

我正在尝试将 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 上,而不是内容。

标签: htmlpython-3.xdjangopdf

解决方案


Javascript 有一个名为print. 您可以使用 print 方法将 HTML 转换为 PDF。这是将 HTML 转换为 PDF 的代码片段。此外,您可以在将 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>

推荐阅读