django动态HTML转PDF方法

本文介绍了一种从数据库动态获取数据并将其填充到HTML模板中,最终生成PDF文件的方法。通过使用pdfkit库和wkhtmltopdf工具,可以实现HTML到PDF的高质量转换。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#从数据库中选择数据
sub_sy2_zts = Sub_SY2_ZT.objects.filter(student=request.user)
sub_sy2_chooses = Sub_SY2_Choose.objects.filter(student=request.user)
sub_sy2_TKs = Sub_SY2_TK.objects.filter(student=request.user)

if sub_sy2_zts.count() == 1 and sub_sy2_chooses.count() == 1 and sub_sy2_TKs.count() == 1: #若数据库中存在数据,将数据读取到前端页面,并生成pdf文件
options = { #关于pdfkit的一些配置
'page-size': 'A3',
'margin-top': '0.75in',
'margin-right': '0.75in',
'margin-bottom': '0.75in',
'margin-left': '0.75in',
'encoding': "UTF-8",
'no-outline': None
}
t = render_to_response("look_experiment2.html", locals()) #变量t为byte类型
config = pdfkit.configuration(wkhtmltopdf=r"D:\Program Files\wkhtmltopdf\bin\wkhtmltopdf.exe")
pdfkit.from_string(t.content.decode("utf-8"), "out.pdf", options=options, configuration=config) # 字符串方式,必须加decode(“utf-8”),否则文件格式不对
return render(request,"look_experiment2.html",locals()) #结束返回读取到数据之后的页面
以上是关于如何动态生成Html到pdf的一段代码示例,希望对大家有所帮助。

转载于:https://www.cnblogs.com/gglll/p/10446711.html

### Django中将HTML换为PDF的库或实现方法Django项目中,将HTML内容换为PDF文件是一个常见的需求。以下是几种常用的库和实现方法: #### 1. 使用 `django-xhtml2pdf` `django-xhtml2pdf` 是一个强大的工具,可以将Django模板直接换为PDF文件[^1]。它基于 `xhtml2pdf` 库,支持CSS样式和复杂的HTML结构。以下是一个简单的示例代码: ```python from django.http import HttpResponse from xhtml2pdf import pisa from django.template.loader import get_template def render_to_pdf(template_src, context_dict={}): template = get_template(template_src) html = template.render(context_dict) response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="output.pdf"' pisa_status = pisa.CreatePDF(html, dest=response) if pisa_status.err: return HttpResponse('We had some errors <pre>' + html + '</pre>') return response ``` 通过上述代码,可以轻松地将HTML模板渲染为PDF文件并返回给用户。 #### 2. 使用 `django-easy-pdf` `django-easy-pdf` 是另一个方便的库,它依赖于 `xhtml2pdf` 和 `reportlab`,并且对Django进行了封装,使其更易于使用[^2]。以下是安装和使用的基本步骤: - 安装依赖: ```bash pip install django-easy-pdf xhtml2pdf>=0.2b1 reportlab ``` - 创建PDF视图: ```python from easy_pdf.views import PDFTemplateView class MyPDFView(PDFTemplateView): template_name = "my_template.html" def get_context_data(self, **kwargs): return super().get_context_data( pagesize="A4", custom_variable="Hello World", **kwargs ) ``` #### 3. 使用 `weasyprint` `weasyprint` 是一个功能强大的工具,支持现代CSS标准,并且可以生成高质量的PDF文件。它不直接与Django集成,但可以通过自定义视图实现[^3]。以下是基本用法: - 安装依赖: ```bash pip install weasyprint ``` - 渲染PDF: ```python from django.http import HttpResponse from weasyprint import HTML def generate_pdf(request): html_string = '<h1>Hello, World!</h1>' html = HTML(string=html_string) pdf_file = html.write_pdf() response = HttpResponse(pdf_file, content_type='application/pdf') response['Content-Disposition'] = 'filename="output.pdf"' return response ``` #### 4. 使用 `reportlab` `reportlab` 是一个低级别的PDF生成库,适合需要完全控制PDF内容的场景。虽然它不直接支持HTMLPDF换,但可以通过手动编写PDF内容来实现复杂的需求[^3]。 ```python from reportlab.pdfgen import canvas from django.http import HttpResponse def print_pdf(request): response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'filename="somefilename.pdf"' p = canvas.Canvas(response) p.drawString(100, 100, "Hello world.") p.showPage() p.save() return response ``` ### 总结 根据具体需求选择合适的库或方法。如果需要简单的HTMLPDF换,推荐使用 `django-xhtml2pdf` 或 `django-easy-pdf`;如果需要更高的定制化和CSS支持,可以选择 `weasyprint`;对于完全自定义的PDF内容,`reportlab` 是最佳选择。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值