I'm developing a web app using python 2.7 with Flask. I'm using xhtml2pdf to generate a pdf based on a template with Jinja2. I want to put an image on the header_frame of the template, but it's only showing on the first page. I tried doing it with text, and it works, the header is shown on all the pages.
Here's the view code:
@report.route('/commissionist/<period>/<commissionist_id>')
@login_required
def commissionist_report(period, commissionist_id):
period_d = periods.Period(datetime.fromtimestamp(mktime(strptime(period, '%m-%Y'))))
carga = load_model.get_commissionist_load(period_d, commissionist_id)
resp = create_pdf(render_template('report/report.html', commissionist_load=carga, period=period, period_datetime=period_d.to_datetime()))
response = make_response(resp)
response.headers['Content-Type'] = 'application/pdf'
response.headers['Content-Disposition'] = 'inline; filename=Informe '+carga.commissionist.name+'.pdf'
return response
Here's the create_pdf function:
def create_pdf(pdf_data):
pdf = StringIO()
pisa.CreatePDF(StringIO(pdf_data), pdf)
resp = pdf.getvalue()
pdf.close()
return resp
And here's the template (the important part):
<!DOCTYPE html>
<html>
<head>
<title>Informe</title>
{% block extra_css %}
<style>
@page {
size: letter portrait;
@frame header_frame { /* Static Frame */
-pdf-frame-content: header_content;
left: 50pt; width: 512pt; top: 50pt; height: 50pt;
}
@frame content_frame { /* Content Frame */
left: 50pt; width: 512pt; top: 110pt; height: 632pt;
}
@frame footer_frame { /* Another static Frame */
-pdf-frame-content: footer_content;
left: 50pt; width: 512pt; top: 772pt; height: 20pt;
}
}
</style>
{% endblock %}
</head>
<body>
{% block body %}
<div id="header_content">
<img src="path\to\file.png" width="25%">
</div>
<div id="footer_content">Página <pdf:pagenumber/>
de <pdf:pagecount/>
</div>
<!--The rest of the html-->
{% endblock %}
</body>
</html>
Hope you can help me. Thanks.
I faced the same trouble at this week, we had some updates on python
and xhtml2pdf
but after 2 hours trying I solved it out.
I'm using xhtml2pdf => 0.2.4
and Python => 3.7
The solution:
I created one generic method to create pdf such as you:
from xhtml2pdf import pisa
from io import StringIO
...
def pdf_converter(self,html):
pisaStatus = pisa.CreatePDF(StringIO(html))
return pisaStatus.dest
Then on view:
@my_bp.route('/...my_root...')
@roles_required('admin')
def export_pdf():
from xxxx.utils.export_pdf import ExportPDF
a = ExportPDF()
pdf = a.pdf_converter(...my_method_that_creates_html...)
pdf.seek(0)
return send_file(pdf, attachment_filename="Report_xxxx.pdf", as_attachment=True)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.