👏

python-docxで日本語フォント対応

2022/12/10に公開

やりたいこと

英語用のフォントと日本語用のフォントを分ける。

以下のページとほぼ同じことしてます。
本家にプルリクエストが入っているみたいですが、テストやドキュメンテーションの不足などでリジェクトされているみたいです。

https://github.com/python-openxml/python-docx/pull/329/commits/097586cab016c10cfaefb3cf283355f74889a27d

使用例

example.py
paragraph.runs[0].font.name = "Arial"
paragraph.runs[0].font.name_eastasia = "MS ゴシック"

モジュールの変更点

docx/oxml/text/font.py
class CT_Fonts(BaseOxmlElement):
    """
    ``<w:rFonts>`` element, specifying typeface name for the various language
    types.
    """
    ascii = OptionalAttribute('w:ascii', ST_String)
    hAnsi = OptionalAttribute('w:hAnsi', ST_String)
+    eastAsia = OptionalAttribute('w:eastAsia', ST_String)
+    hint = OptionalAttribute('w:hint', ST_String)

# 中略

    @rFonts_hAnsi.setter
    def rFonts_hAnsi(self, value):
        if value is None and self.rFonts is None:
            return
        rFonts = self.get_or_add_rFonts()
        rFonts.hAnsi = value

+    @property
+    def rFonts_eastAsia(self):
+        """
+        The value of `w:rFonts/@w:eastAsia` or |None| if not present.
+        """
+        rFonts = self.rFonts
+        if rFonts is None:
+            return None
+        return rFonts.eastAsia+
+
+    @rFonts_eastAsia.setter
+    def rFonts_eastAsia(self, value):
+        if value is None and self.rFonts is None:
+            return
+        rFonts = self.get_or_add_rFonts()
+        rFonts.eastAsia = value
+
+    @property
+    def rFonts_hint(self):
+        """
+        The value of `w:rFonts/@w:hint` or |None| if not present.
+        """
+        rFonts = self.rFonts
+        if rFonts is None:
+            return None
+        return rFonts.hint
+
+    @rFonts_hint.setter
+    def rFonts_hint(self, value):
+        if value is None and self.rFonts is None:
+            return
+        rFonts = self.get_or_add_rFonts()
+        rFonts.hint = value
docx/text/font.py
    @name.setter
    def name(self, value):
        rPr = self._element.get_or_add_rPr()
        rPr.rFonts_ascii = value
        rPr.rFonts_hAnsi = value

+    @property
+    def name_eastasia(self):
+        """
+        Get or set the typeface name for this |Font| instance, causing the
+        text it controls to appear in the named font, if a matching font is
+        found. |None| indicates the typeface is inherited from the style
+        hierarchy.
+        """
+        rPr = self._element.rPr
+        if rPr is None:
+            return None
+        return rPr.rFonts_eastAsia
+
+    @name_eastasia.setter
+    def name_eastasia(self, value):
+        rPr = self._element.get_or_add_rPr()
+        rPr.rFonts_eastAsia = value
+        rPr.rFonts_hint = "eastAsia"
+

Discussion