Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

为什么中文会出现乱码,如何解决 #64

Open
vdjango opened this issue Oct 27, 2018 · 2 comments
Open

为什么中文会出现乱码,如何解决 #64

vdjango opened this issue Oct 27, 2018 · 2 comments

Comments

@vdjango
Copy link

vdjango commented Oct 27, 2018

为什么中文会出现乱码,如何解决

@vdjango
Copy link
Author

vdjango commented Oct 31, 2018

好吧,既然没人说话,那就我补充一下解决方案吧:

很简单,只需要修改一个文件,添加一个文件,共2处位置,就可以实现中文喽!
先来看看效果吧
image

安装 django-easy-pdf 后,找到它的位置 [Python36\Lib\site-packages\xhtml2pdf]
我们修改的是 xhtml2pdf 所以是这个路径,因为安装django-easy-pdf 的时候会安装上他

然后我们找到这个路径
Python36\Lib\site-packages\xhtml2pdf\default.py

DEFAULT_FONT = { 
    "courier": "Courier",
    "courier-bold": "Courier-Bold",
    "courier-boldoblique": "Courier-BoldOblique",
    "courier-oblique": "Courier-Oblique",

    # 修改这一行为 ["helvetica": "SimHei"]
    "helvetica": "helvetica", 
    
    # SimHei 为黑体,是系统的自带字体大部分系统都有这个字体,所以就用了它
    "helvetica": "SimHei"
    
    ........
}

然后在这里添加并注册字体
Python36\Lib\site-packages_init_,py

from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont

# 只要你系统中存在这个字体,就可以这样写,这里的SimHei.ttf我没有添加如何路径哦,它会从系统字库里面找
pdfmetrics.registerFont(TTFont('SimHei', 'SimHei.ttf'))

# 这一个方法,只有这个字体xhtml2pdf内部存在时可用
# from reportlab.pdfbase.cidfonts import UnicodeCIDFont
# pdfmetrics.registerFont(UnicodeCIDFont('STSong-Light'))

完整的例子:
Python36\Lib\site-packages\xhtml2pdf\default.py

DEFAULT_FONT = { 
    "courier": "Courier",
    "courier-bold": "Courier-Bold",
    "courier-boldoblique": "Courier-BoldOblique",
    "courier-oblique": "Courier-Oblique", 
    "helvetica": "SimHei"
    ........
}

Python36\Lib\site-packages_init_,py

from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont

pdfmetrics.registerFont(TTFont('SimHei', 'SimHei.ttf'))

@marksweb
Copy link

marksweb commented Nov 5, 2020

I know it's a few years later, but we've got unicode working just now by adding this meta to the template;

<meta http-equiv=Content-Type content="text/html;charset=utf-8">

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants