binary-husky/gpt_academic · error · Exception

转换PDF失败: {str(e)}

Error message

转换PDF失败: {str(e)}

What it means

Catch-all wrapper around WordToPdfConverter.convert_to_pdf: any failure during conversion (missing LibreOffice, LibreOffice conversion error, os.rename failure because the output PDF was never produced, docx2pdf/Word COM errors on Windows) is re-raised as '转换PDF失败: {cause}'. The inner message identifies the true failure; for missing LibreOffice the inner message is error 64.

Source

Thrown at crazy_functions/paper_fns/file2file_doc/word2pdf.py:56

                # Linux系统需要安装libreoffice
                if not os.system('which libreoffice') == 0:
                    raise RuntimeError("请先安装LibreOffice: sudo apt-get install libreoffice")

                # 使用libreoffice进行转换
                os.system(f'libreoffice --headless --convert-to pdf "{word_path}" --outdir "{pdf_path.parent}"')

                # 如果输出路径与默认生成的不同,则重命名
                default_pdf = word_path.with_suffix('.pdf')
                if default_pdf != pdf_path:
                    os.rename(default_pdf, pdf_path)
            else:
                # Windows和MacOS使用docx2pdf
                convert(word_path, pdf_path)

            return str(pdf_path)

        except Exception as e:
            raise Exception(f"转换PDF失败: {str(e)}")

    @staticmethod
    def batch_convert(word_dir: Union[str, Path], pdf_dir: Union[str, Path] = None) -> list:
        """
        批量转换目录下的所有Word文档

        参数:
            word_dir: 包含Word文档的目录路径
            pdf_dir: 可选,PDF文件的输出目录。如果未指定,将使用与Word文档相同的目录

        返回:
            生成的PDF文件路径列表
        """
        word_dir = Path(word_dir)
        if pdf_dir:
            pdf_dir = Path(pdf_dir)
            pdf_dir.mkdir(parents=True, exist_ok=True)

View on GitHub (pinned to d6bde0fa54)

Solutions

  1. Read the inner message after '转换PDF失败:' — it pinpoints the sub-failure
  2. Verify LibreOffice works standalone: libreoffice --headless --convert-to pdf file.docx --outdir /tmp
  3. Ensure pdf_path.parent exists (os.makedirs(pdf_path.parent, exist_ok=True)) before converting
  4. Kill stale soffice processes (pkill soffice) that lock the headless profile, then retry
  5. Check the docx opens in Word/LibreOffice GUI — corrupt inputs are a common cause

Example fix

// before
os.system(f'libreoffice --headless --convert-to pdf "{word_path}" --outdir "{pdf_path.parent}"')

// after
import subprocess
os.makedirs(pdf_path.parent, exist_ok=True)
result = subprocess.run(['libreoffice','--headless','--convert-to','pdf',str(word_path),'--outdir',str(pdf_path.parent)], capture_output=True)
if result.returncode != 0:
    raise RuntimeError(f"libreoffice failed: {result.stderr.decode()}")
Defensive patterns

Strategy: try-catch

Validate before calling

from pathlib import Path
import shutil, platform

def precheck(word_path, pdf_path):
    p = Path(pdf_path if pdf_path else Path(word_path).with_suffix('.pdf'))
    p.parent.mkdir(parents=True, exist_ok=True)
    assert Path(word_path).exists()
    if platform.system() == 'Linux':
        assert shutil.which('libreoffice'), 'libreoffice missing'

Try / catch

try:
    out = WordToPdfConverter.convert_to_pdf(docx, pdf)
except Exception as e:
    msg = str(e)
    if 'LibreOffice' in msg: install_or_skip()
    elif 'No such file' in msg: fix_output_dir_and_retry()
    else: raise

Prevention

When it happens

Trigger: libreoffice --headless runs but exits non-zero (corrupt docx, permission issue, profile lock); the expected default PDF file is not created so os.rename raises FileNotFoundError; docx2pdf fails on Windows when MS Word is not installed; pdf_path.parent does not exist.

Common situations: Converting a password-protected or malformed .doc file; a leftover LibreOffice headless process locking the user profile; output directory not created beforehand; spaces/quotes in paths breaking the os.system shell command.

Related errors


AI-assisted analysis of binary-husky/gpt_academic@d6bde0fa54 (2026-08-14). Data as JSON: /api/errors/7086318fd9468795. Report an issue: GitHub.