python使用fpdf中文乱码问题的排查

先说结论

1. 使用如下代码,main.py目录下SimHei.ttf

        class PDF(FPDF):
            def header(self):
                if self.page_no()>1:
                    self.set_y(10)
                    self.set_font('SimHei', '', 10)  
                    self.cell(0, 10, title, 0, 1, 'C') 
       
            def footer(self):
                if self.page_no()>1:
                    self.set_y(-10)
                    self.set_font('SimHei', '', 10)
                    self.cell(0, 10, f'第 {self.page_no()-1} 页', 0, 1, 'C') 
            
        pdf = PDF()
        pdf.add_font('SimHei', '', "SimHei.ttf", uni=True)
        pdf.set_font('SimHei', '', 12)
        pdf.add_page()
pdf.set_margins(10, 10, 10)
pdf.set_auto_page_break(auto=True, margin=10) 

2. 所有写入的内容是UTF-8编码

 

如果是乱码排查方式:

1. 写入的字符串使用cchardet检测编码类型,如果不是utf-8,请使用

import cchardet

# 字符串内容
text = '这是一个测试字符串'

# 转换为字节流(假设原来的编码是 utf-8)
raw_bytes = text.encode('utf-8')

# 检测编码
result = cchardet.detect(raw_bytes)
print(f'检测到的编码格式为:{result["encoding"]}, 置信度为:{result["confidence"]}')

2. 写入的文件是request读取的远端文件,则要求远端文件是utf-8编码,读取的以UTF-8编码读取,

           response = requests.get(files[current_index]['fileurl'])
           response.encoding = 'utf-8'

 

posted @ 2025-05-31 09:52  四代土豆2  阅读(70)  评论(0)    收藏  举报