Flask 生成pdf并下载

it2025-12-12  1

生成pdf的方法千千万万,在这里我用来pdfkit 来作为工具包,具体怎么安装请百度查询安装教程(要安装wkhtmltopdf这个东西,在代码中需要调用它,有时间的话我会来再出一篇如何安装这个工具的文章),在这里只介绍如何生成pdf并且下载到本地;

话不多说,直接贴代码:

path_wk = r'\wkhtmltopdf.exe' # 安装位置 options = { 'page-size': 'Letter', 'margin-top': '0.75in', 'margin-right': '0.75in', 'margin-bottom': '0.75in', 'margin-left': '0.75in', 'encoding': "UTF-8", 'custom-header': [ ('Accept-Encoding', 'gzip') ], 'no-outline': None, 'outline-depth': 10, 'javascript-delay': 15000 } # 这些配置是控制pdf的界面显示的,类似css里面的内容 config = pdfkit.configuration(wkhtmltopdf=path_wk) # str = getHtml() # 如果你想用html生成pdf,可以自己封装一个gethtml()的函数,返回html字符串就行了 if html: str = str.replace("BODYCONTENT", html) time.sleep(3) pdf_pdf = pdfkit.from_string(str, False, css=r'CSS代码的绝对路径,一定要是绝对路径\main.css', configuration=config) else: pdf_pdf = pdfkit.from_url('./pdfTemp.html', False, configuration=config) #pdfkit.from_url() return pdf_pdf

有几个需要注意的地方:

1,wkhtmltopdf这个配置的路径 2,想好你要用字符串来生成pdf还是html内容或者是url来生成分别对应(from_url,from_file,from_string) 3,配置之中如果要显示中文,别忘了配置编码方式

上面结束,我们就可以从内存中拿到刚才生成的pdf,直接调用上面的函数,在我这里是用的html生成pdf,然后给前端下载:

如何下载,请看下面

@api.route("/report/download_PDF", methods=["GET", "POST"]) def download_PDF(): BodyStr=""" abcd """ # 替换成你要生成pdf的html字符串,也可以让前端传过来 attachment = make_pdf(BodyStr) response = make_response(attachment) response.headers['Content-type'] = 'application/pdf' # 指定返回的类型 nowtime = datetime.datetime.now().strftime('%Y%m%d%H') response.headers['ContentDisposition']='attachment;filename=CoolingReport'+nowtime+'.pdf' return response

如上代码,调用生成pdf的函数,然后使用flask中自带的make_response()方法,传入pdf数据,然后设置响应内容和配置,返回给前端,就完成了下载的操作!

最新回复(0)