#從數據庫中選擇數據
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的一段代碼示例,希望對大家有所幫助。