Home  >  Article  >  Backend Development  >  How to set Chinese fonts in python docx

How to set Chinese fonts in python docx

不言
不言Original
2018-05-08 13:44:487191browse

This article mainly introduces the operation method of setting Chinese fonts in python docx. It has certain reference value. Now I share it with you. Friends in need can refer to it.

I have recently used docx to generate word documents. , docx itself is very convenient to use, and the various styles it comes with are very beautiful. The only drawback is that the support for Chinese is not good enough. When the Chinese font is not set, although the generated document can display Chinese, the strokes are of different sizes and are ugly.

Solution:

First create a document and declare a document:


from docx import Document
document = Document()


The built-in styles of docx can be obtained through document.styles.

The text is Normal, and the heading styles are based on the title declaration, from Heading 1 to Heading 9. There are also styles corresponding to various words such as table and list. It can be viewed by traversing document.styles.

Let’s take the text Normal as an example. Let's first take a look at which properties in the style object are involved in font changes.

1. document.styles['Normal'].font.name

Students who are interested in in-depth research can take a look at the official documentation Introduction to Font

http://python-docx.readthedocs.io/en/latest/dev/analysis/features/text/font.html?highlight=font

Here we only font.name needs to be changed.

2. document.styles['Normal']._element.rPr.rFonts

Just changing font.name is not enough, you also need to call ._element.rPr The set() method of .rFonts.

To put it all together


##

from docx.oxml.ns import qn
document.styles['Normal'].font.name = u'宋体'
document.styles['Normal']._element.rPr.rFonts.set(qn('w:eastAsia'), u'宋体')


Problem solution, form The font in Chinese was successfully changed to "Song Ti".

Related recommendations:


How to read and write docx files in Python



The above is the detailed content of How to set Chinese fonts in python docx. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn