binary-husky/gpt_academic · error · Exception

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

Error message

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

What it means

This is a catch-all wrapper: convert_to_pdf catches any Exception from the actual conversion step and re-raises it as `Exception("转换PDF失败: ...")`, keeping the original message in str(e). On Linux the inner failure is almost always the libreoffice subprocess (os.system returns non-zero, output PDF never created, or the os.rename at the end fails with FileNotFoundError); on Windows/macOS it comes from docx2pdf's convert(), which requires MS Word to be installed.

Source

Thrown at crazy_functions/review_fns/conversation_doc/word2pdf.py:65

                # 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. Run the exact libreoffice command manually to see the real error: libreoffice --headless --convert-to pdf "file.docx" --outdir /tmp, and use the str(e) text to identify the cause.
  2. Ensure the output directory (pdf_path.parent) exists before calling convert_to_pdf (pdf_path.parent.mkdir(parents=True, exist_ok=True)).
  3. Serialize concurrent conversions or give each call a separate HOME/-env:UserInstallation profile so headless libreoffice instances do not collide.
  4. On Windows/macOS, install/repair MS Word — docx2pdf is only a COM/AppleScript bridge and cannot work without it.
  5. Verify the input is a genuine .docx (zip with word/ inside) before conversion.

Example fix

# before
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)

# after
code = subprocess.call(['libreoffice', '--headless', '--convert-to', 'pdf', str(word_path), '--outdir', str(pdf_path.parent)])
default_pdf = word_path.with_suffix('.pdf')
if not default_pdf.exists():
    raise RuntimeError(f'libreoffice conversion failed with exit code {code}')
if default_pdf != pdf_path:
    pdf_path.parent.mkdir(parents=True, exist_ok=True)
    os.replace(default_pdf, pdf_path)
Defensive patterns

Strategy: try-catch

Validate before calling

from pathlib import Path
import zipfile

def is_valid_docx(p: str) -> bool:
    p = Path(p)
    return p.exists() and zipfile.is_zipfile(p) and 'word/' in zipfile.ZipFile(p).namelist()

Try / catch

try:
    out = WordToPdfConverter.convert_to_pdf(word, pdf)
except Exception as e:
    logger.error('pdf conversion failed: %s', e)  # str(e) embeds the real cause
    # degrade: keep the .docx and notify the user instead of failing the whole job
    return None

Prevention

When it happens

Trigger: libreoffice prints an error and does not produce word_path.pdf (corrupt .docx, file path with characters libreoffice mishandles, or another libreoffice instance holds the profile lock); the produced default_pdf does not exist so os.rename raises; on Windows/macOS, docx2pdf.convert() fails because Word is not installed or the COM automation cannot start.

Common situations: Concurrent conversions on Linux (libreoffice headless fails when ~/.config/libreoffice is locked by another instance); converting a file that is not a real docx (renamed .txt); running docx2pdf on a machine without MS Office; passing a pdf_path in a directory that does not exist so the rename fails.

Related errors


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