django动态HTML转PDF方法

#从数据库中选择数据
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的一段代码示例,希望对大家有所帮助。

猜你喜欢

转载自www.cnblogs.com/gglll/p/10446711.html