html - 在 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 上,而不是内容。
解决方案
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>
推荐阅读
- shell - “exec $SHELL”有什么作用?
- r - 通过闪亮的 removeUI() 函数删除 actionButton()
- ios - FOLDINGCELL:线程 1:致命错误:在展开可选值时意外发现 nil
- python - 我如何检查我的下一次 Airflow DAG 运行是否已为特定 dag 安排?
- javascript - 如何创建一个自动 html 输入文本字段来显示从 API 获取的值?
- node.js - NodeJS+Express:Passport 与 OAuth2 的范围(访问权限)
- java - Birt 报告 - IReportEngineFactory 为空
- c++ - c++ delete[] 2d array 导致堆损坏
- ios - 用于应用程序扩展的 IB 故事板:iPad 图标不存在、尺寸不变、方向不工作
- ios - iPhone 8 / iPhone X 上的超长 wifi 请求旅行时间