+
99
-

回答

通常是因为系统缺少中文字体或字体配置不正确。以下是详细的解决方案和步骤:

解决方案1. 安装中文字体

确保系统中安装了常用的中文字体,例如:

文泉驿正黑(WenQuanYi Zen Hei)思源黑体(Source Han Sans)宋体(SimSun)步骤:

安装字体包在 CentOS 中,可以通过以下命令安装中文字体:

sudo yum install -y wqy-microhei-fonts wqy-zenhei-fonts

如果需要更多字体,可以手动下载并安装。例如:

下载 思源黑体 或其他中文字体。将字体文件复制到 /usr/share/fonts/ 目录下:
sudo cp *.ttf /usr/share/fonts/

更新字体缓存安装字体后,更新字体缓存以确保系统识别新字体:

sudo fc-cache -fv

验证字体安装使用以下命令检查是否成功安装中文字体:

fc-list :lang=zh

输出应包含已安装的中文字体列表。

2. 配置 LibreOffice 字体映射

即使系统中安装了中文字体,LibreOffice 可能未正确映射字体。需要手动配置字体替换规则。

步骤:

编辑字体配置文件LibreOffice 的字体配置文件通常位于以下路径:

~/.config/libreoffice/4/user/

如果不存在,可以手动创建。

创建字体替换规则创建一个名为 user.xml 的文件,并添加字体替换规则。例如:

<oor:items xmlns:oor="http://openoffice.org/2001/registry">
    <item oor:path="/org.openoffice.Office.Common/Font/Substitution">
        <prop oor:name="SubstituteFont" oor:type="xs:string">
            <value>WenQuanYi Zen Hei</value>
        </prop>
    </item>
</oor:items>

重启 LibreOffice修改配置后,重新启动 soffice 服务以应用更改。

3. 设置环境变量

在无头模式下运行 soffice 时,需要确保字体配置被正确加载。

步骤:

设置字体路径在运行 soffice 命令前,设置以下环境变量:

export FONTCONFIG_PATH=/etc/fonts
export FONTCONFIG_FILE=/etc/fonts/fonts.conf

运行 soffice在同一终端中运行转换命令:

soffice --headless --convert-to pdf --outdir /path/to/output /path/to/example.pptx
4. 测试转换

完成上述配置后,再次尝试转换 .pptx 文件为 PDF 或图片,检查中文是否正常显示。

示例代码

如果您希望通过 Python 脚本实现自动化转换,可以结合字体配置和 subprocess 模块调用 soffice。

import os
import subprocess

def convert_to_pdf(input_file, output_dir):
    # 确保输出目录存在
    if not os.path.exists(output_dir):
        os.makedirs(output_dir)

    # 设置字体环境变量
    env = os.environ.copy()
    env["FONTCONFIG_PATH"] = "/etc/fonts"
    env["FONTCONFIG_FILE"] = "/etc/fonts/fonts.conf"

    # 构造 LibreOffice 命令
    command = [
        "soffice", "--headless", "--convert-to", "pdf",
        "--outdir", output_dir, input_file
    ]

    # 执行命令
    try:
        result = subprocess.run(command, check=True, capture_output=True, text=True, env=env)
        print(result.stdout)
    except subprocess.CalledProcessError as e:
        print("Error:", e.stderr)

# 示例调用
input_file = "example.pptx"
output_folder = "output_pdfs"
convert_to_pdf(input_file, output_folder)
注意事项

字体一致性确保使用的字体与文档中的字体一致。如果文档中使用了特定字体(如宋体),需要安装该字体。

分辨率设置如果转换为图片时中文仍然模糊,可以尝试提高分辨率:

soffice --headless --convert-to png:"draw_png_Export:AntiAliasing=1 Resolution=300" --outdir /path/to/output /path/to/example.pptx

调试日志如果问题仍未解决,可以启用 LibreOffice 的调试日志以查看详细错误信息:

soffice --headless --convert-to pdf --outdir /path/to/output /path/to/example.pptx --log-file /tmp/soffice.log

网友回复

我知道答案,我要回答