Django生成PDF文档显示网页上以及PDF中文显示乱码的解决方法
作者:Pykk2019 时间:2022-01-05 22:02:07
项目地址:https://github.com/PythonerKK/django-generate-pdf/tree/master
这个demo实现了通过用户输入自己的个人信息生成一份简历pdf,来阐述如何使用Django的HttpResponse生成PDF的文档。
先上效果图:
安装依赖库
首先安装Django最新版2.2.2和PDF依赖包xhtml2pdf
pip install django
pip install xhtml2pdf
编写表单验证
为了简单起见,这个demo依赖数据库,只需要表单验证数据即可
pdf/forms.py
class MessageForm(forms.Form):
'''
表单验证
'''
name = forms.CharField(required=True)
degree = forms.CharField(required=True)
edu = forms.CharField(required=True)
work = forms.CharField(required=True)
tech = forms.CharField(required=True)
phone = forms.CharField(required=True)
编写类视图
pdf/views.py
由于这里我们只需要表单视图,所以只创建了一个类视图,post用来验证表单数据是否都存在,如果存在就把表单数据渲染到PDF模板中,经过处理后返回PDF的响应response。
这里可以使用Django的通用类视图FormView构建,代码更简洁
class MessageView(View):
def get(self, request):
form = MessageForm(data=request.GET)
return render(request, 'index.html', {
'form': form
})
def post(self, request):
form = MessageForm(data=request.POST)
if form.is_valid():
response = generate_pdf_response(context=form.cleaned_data)
return response
return redirect(reverse('pdf:message'))
编写生成PDF响应response
view.py这里为了方便直接把处理函数写到视图函数的文件里
def link_callback(uri):
if uri.startswith(settings.MEDIA_URL):
path = os.path.join(settings.MEDIA_ROOT,
uri.replace(settings.MEDIA_URL, ""))
elif uri.startswith(settings.STATIC_URL):
path = os.path.join(settings.STATIC_ROOT,
uri.replace(settings.STATIC_URL, ""))
else:
return uri
# 确保本地文件存在
if not os.path.isfile(path):
raise Exception(
"Media URI 必须以以下格式开头"
f"'{settings.MEDIA_URL}' or '{settings.STATIC_URL}'")
return path
def generate_pdf_response(context):
response = HttpResponse(content_type="application/pdf")
response["Content-Disposition"] = \
f"attachment; filename='{context['name']}.pdf'"
html = render_to_string("pdf.html", context=context)
status = pisa.CreatePDF(html,
dest=response,
link_callback=link_callback)
if status.err:
return HttpResponse("PDF文件生成失败")
return response
解决中文乱码问题
需要下载中文字体msyh.ttf放在static目录下的font目录,用来设置全局字体。这些文件都在github仓库里。
def font_patch():
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.pdfbase import pdfmetrics
from xhtml2pdf.default import DEFAULT_FONT
pdfmetrics.registerFont(TTFont('yh', '{}/font/msyh.ttf'.format(
settings.STATICFILES_DIRS[0])))
DEFAULT_FONT['helvetica'] = 'yh'
把这个函数放在生成PDF响应前
按照以上大致步骤大家就能够生成PDF文件了,可以在网页中浏览、放大、缩小,也可以下载,非常方便、简单。
大家可以直接clone一份代码试试效果
来源:https://www.cnblogs.com/PyKK2019/p/11129471.html
标签:Django,PDF文档,中文乱码
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
PyTorch搭建LSTM实现时间序列负荷预测
2023-08-18 09:10:09
![](https://img.aspxhome.com/file/2023/9/76999_0s.png)
CSS样式表中继承关系的空格与不空格
2007-12-12 13:05:00
JavaScript缓动动画函数的封装方法
2023-08-07 10:48:26
Mysql中limit的用法方法详解与注意事项
2023-11-16 09:20:05
TensorFlow神经网络学习之张量与变量概念
2023-07-06 20:58:02
![](https://img.aspxhome.com/file/2023/1/79591_0s.png)
Django学习笔记之ORM基础教程
2022-07-25 22:59:07
![](https://img.aspxhome.com/file/2023/2/78722_0s.png)
使用FCKeditor添加文章时,在文章最后多了逗号
2007-10-11 13:38:00
如何在MySQL数据库中使用XML数据
2009-12-29 10:48:00
python爬虫基础之urllib的使用
2022-02-10 19:01:18
sqlalchemy实现时间列自动更新教程
2021-08-18 20:12:58
python标准库random模块处理随机数
2023-11-23 16:22:49
通过不同的CSS设计字体大小来提高用户体验
2008-12-10 19:17:00
Asp性能优化之Response.IsClientConnected属性及其应用示例
2008-09-18 12:13:00
django 模版关闭转义方式
2023-07-18 15:23:03
![](https://img.aspxhome.com/file/2023/1/70201_0s.jpg)
python脚本框架webpy入门安装及应用创建
2023-08-23 05:08:51
网页语言编码及asp乱码问题解决方案
2008-01-31 13:21:00
asp如何设定程序的执行次数?
2010-05-18 18:31:00
js实现千分符和保留几位小数的简单实例
2023-08-21 10:03:26
趣用文化元素
2009-09-03 11:53:00
![](https://img.aspxhome.com/file/UploadPic/20099/3/0909-using_culture_elements-01-12s.jpg)
RSS2.0规范中文版
2008-06-25 13:53:00