使用fitz向PDF插入俄文文本失败,请求排查问题
俄文文本插入PDF显示异常的解决方法
尝试向PDF文件中插入俄文文本时显示异常,代码如下:
import fitz if __name__ == '__main__': src_pdf_filename = 'original.pdf' dst_pdf_filename = 'destination.pdf' document = fitz.open(src_pdf_filename) ss = u"ToUnicode Привет Hello" for page in document: page.insert_text((50, 250), ss, fontname="Times-Roman", fontsize=50,encoding=fitz.TEXT_ENCODING_CYRILLIC, overlay=False) document.save(dst_pdf_filename) document.close()
错误原因
Times-Roman是PDF内置的基础字体,仅支持拉丁字符集,不包含西里尔字母。哪怕指定了encoding=fitz.TEXT_ENCODING_CYRILLIC,没有对应字体支持的情况下,俄文无法正确渲染,导致显示异常。
解决方法
方案1:使用系统自带的俄文兼容字体
大部分操作系统自带支持西里尔字母的字体,比如Windows的Times New Roman、Linux的Liberation Serif、macOS的Georgia,直接替换fontname参数即可:
import fitz if __name__ == '__main__': src_pdf_filename = 'original.pdf' dst_pdf_filename = 'destination.pdf' document = fitz.open(src_pdf_filename) ss = "ToUnicode Привет Hello" for page in document: page.insert_text( (50, 250), ss, fontname="Times New Roman", # 替换为系统支持的俄文兼容字体名 fontsize=50, encoding=fitz.TEXT_ENCODING_CYRILLIC, overlay=False ) document.save(dst_pdf_filename) document.close()
方案2:加载外部俄文专用字体文件
如果系统没有合适的字体,可以下载支持西里尔字母的字体文件(如带俄文的Times New Roman字体文件),通过fitz.Font()注册后使用:
import fitz if __name__ == '__main__': src_pdf_filename = 'original.pdf' dst_pdf_filename = 'destination.pdf' font_file_path = "your-font-path/cyrillic-font.ttf" # 替换为你的字体文件路径 document = fitz.open(src_pdf_filename) # 注册外部字体 cyrillic_font = fitz.Font(fontfile=font_file_path) ss = "ToUnicode Привет Hello" for page in document: page.insert_text( (50, 250), ss, fontname=cyrillic_font.name, fontsize=50, overlay=False ) document.save(dst_pdf_filename) document.close()
注意事项
- 确认使用的字体确实支持西里尔字母,避免下载仅包含拉丁字符的版本。
- 不同系统的字体名称可能有差异,比如Linux下推荐用
Liberation Serif,macOS可直接用Times New Roman。
内容的提问来源于stack exchange,提问作者Дмитрий Федулов
相关产品推荐
相关产品推荐

