Official website: https://pypi.org/project/django-xhtml2pdf/
1. Create a new project to install django django-xhtml2pdf
pip install django-xhtml2pdf
2.views.py
from django_xhtml2pdf.utils import pdf_decorator @pdf_decorator(pdfname=str(time.strftime('%Y-%m-%d-%H-%M-%S',time.localtime())) + str(random.random()) + ".pdf") def pdf(request): return render(request, "pdf.html")
3. Solve the problem of Chinese garbled
New font in the project directory structure static static directory -> font
Download msyh.ttf
4. Set setting.py
from reportlab.pdfbase.ttfonts import TTFont from reportlab.pdfbase import pdfmetrics FONT_PATH = os.path.join(BASE_DIR, r'cjystatic\font\msyh.ttf') # 公钥 pdfmetrics.registerFont(TTFont('yh', FONT_PATH)) from xhtml2pdf.default import DEFAULT_FONT DEFAULT_FONT["helvetica"] = 'yh'
The operating results