我正在尝试转换一个使用相当引导和样式的 HTML 页面。我尝试了从reportlab到weasyprint再到xhtml2pdf的所有方法,但没有任何效果!我在网上没有找到任何东西可以帮助我完成这个简单的任务。我什至尝试寻找可以完成此类工作的付费 API。实现这一目标的最佳方法是什么?
使用 HTML 模板通过 render_to_pdf 实用函数创建 PDF 的指南。
打开您的 Django 项目或创建一个空白项目
安装xhtml2pdf文档:
使用Python 3
pip install --pre xhtml2pdf
使用Python 2
pip install xhtml2pdf
将 utils.py 模块添加到您的项目中:
编写render_to_pdf函数:
from io import BytesIO
from django.http import HttpResponse
from django.template.loader import get_template
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("ISO-8859-1")), result)
if not pdf.err:
return HttpResponse(result.getvalue(), content_type='application/pdf')
return None
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Title</title>
<style type="text/css">
body {
font-weight: 200;
font-size: 14px;
}
.header {
font-size: 20px;
font-weight: 100;
text-align: center;
color: #007cae;
}
.title {
font-size: 22px;
font-weight: 100;
/* text-align: right;*/
padding: 10px 20px 0px 20px;
}
.title span {
color: #007cae;
}
.details {
padding: 10px 20px 0px 20px;
text-align: left !important;
/*margin-left: 40%;*/
}
.hrItem {
border: none;
height: 1px;
/* Set the hr color */
color: #333; /* old IE */
background-color: #fff; /* Modern Browsers */
}
</style>
</head>
<body>
<div class='wrapper'>
<div class='header'>
<p class='title'>Invoice # </p>
</div>
<div>
<div class='details'>
Bill to: <br/>
Amount: <br/>
Date:
<hr class='hrItem' />
</div>
</div>
</body>
</html>
from django.http import HttpResponse
from django.views.generic import View
from yourproject.utils import render_to_pdf #created in step 4
class GeneratePdf(View):
def get(self, request, *args, **kwargs):
data = {
'today': datetime.date.today(),
'amount': 39.99,
'customer_name': 'Cooper Mann',
'order_id': 1233434,
}
pdf = render_to_pdf('pdf/invoice.html', data)
return HttpResponse(pdf, content_type='application/pdf')
class GeneratePDF(View):
def get(self, request, *args, **kwargs):
template = get_template('invoice.html')
context = {
"invoice_id": 123,
"customer_name": "John Cooper",
"amount": 1399.99,
"today": "Today",
}
html = template.render(context)
pdf = render_to_pdf('invoice.html', context)
if pdf:
response = HttpResponse(pdf, content_type='application/pdf')
filename = "Invoice_%s.pdf" %("12341231")
content = "inline; filename='%s'" %(filename)
download = request.GET.get("download")
if download:
content = "attachment; filename='%s'" %(filename)
response['Content-Disposition'] = content
return response
return HttpResponse("Not found")
如果我们有静态 css 文件,并且数据也是来自数据库的动态数据,那么如何将 html 转换为 pdf 提供解决此问题的指南?