要在PDF中设置页脚,使用Python的Django框架结合Pisa库是一个不错的选择
pip install django
pip install pisa
from django.http import HttpResponse
from django.template.loader import get_template
from xhtml2pdf import pisa
def render_pdf_with_footer(request):
# 获取PDF模板
template = get_template('pdf_template.html')
context = {'title': 'PDF with Footer'}
# 渲染模板
html = template.render(context)
# 创建PDF响应
response = HttpResponse(content_type='application/pdf')
response['Content-Disposition'] = 'attachment; filename="pdf_with_footer.pdf"'
# 设置页脚
def footer_renderer(canvas, doc):
canvas.saveState()
canvas.setFont('Helvetica', 9)
canvas.drawString(10, 10, 'Footer Text')
canvas.restoreState()
# 创建PDF文档并渲染
pisa_status = pisa.CreatePDF(html, dest=response, footer_callback=footer_renderer)
if pisa_status.err:
return HttpResponse('We had some errors <pre>' + html + '</pre>')
return response
urls.py
文件中添加一个URL模式,将请求映射到刚刚创建的视图函数:from django.urls import path
from . import views
urlpatterns = [
path('pdf-with-footer/', views.render_pdf_with_footer, name='pdf_with_footer'),
]
pdf_template.html
,用于定义PDF的内容:<!DOCTYPE html>
<html>
<head>
<title>{{ title }}</title>
</head>
<body>
<h1>{{ title }}</h1>
<p>This is a sample PDF with a footer.</p>
</body>
</html>
现在,当你访问/pdf-with-footer/
URL时,Django将渲染PDF并在其中设置页脚。
领取专属 10元无门槛券
手把手带您无忧上云