{"record":{"id":"7086318fd9468795","repo":"binary-husky/gpt_academic","slug":"pdf-str-e-708631","errorCode":null,"errorMessage":"转换PDF失败: {str(e)}","messagePattern":"转换PDF失败: (.+?)","errorType":"exception","errorClass":"Exception","httpStatus":null,"severity":"error","filePath":"crazy_functions/paper_fns/file2file_doc/word2pdf.py","lineNumber":56,"sourceCode":"                # Linux系统需要安装libreoffice\n                if not os.system('which libreoffice') == 0:\n                    raise RuntimeError(\"请先安装LibreOffice: sudo apt-get install libreoffice\")\n\n                # 使用libreoffice进行转换\n                os.system(f'libreoffice --headless --convert-to pdf \"{word_path}\" --outdir \"{pdf_path.parent}\"')\n\n                # 如果输出路径与默认生成的不同，则重命名\n                default_pdf = word_path.with_suffix('.pdf')\n                if default_pdf != pdf_path:\n                    os.rename(default_pdf, pdf_path)\n            else:\n                # Windows和MacOS使用docx2pdf\n                convert(word_path, pdf_path)\n\n            return str(pdf_path)\n\n        except Exception as e:\n            raise Exception(f\"转换PDF失败: {str(e)}\")\n\n    @staticmethod\n    def batch_convert(word_dir: Union[str, Path], pdf_dir: Union[str, Path] = None) -> list:\n        \"\"\"\n        批量转换目录下的所有Word文档\n\n        参数:\n            word_dir: 包含Word文档的目录路径\n            pdf_dir: 可选，PDF文件的输出目录。如果未指定，将使用与Word文档相同的目录\n\n        返回:\n            生成的PDF文件路径列表\n        \"\"\"\n        word_dir = Path(word_dir)\n        if pdf_dir:\n            pdf_dir = Path(pdf_dir)\n            pdf_dir.mkdir(parents=True, exist_ok=True)\n","sourceCodeStart":38,"sourceCodeEnd":74,"githubUrl":"https://github.com/binary-husky/gpt_academic/blob/d6bde0fa54373309bd05823a49bda8da019d2c77/crazy_functions/paper_fns/file2file_doc/word2pdf.py#L38-L74","documentation":"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.","triggerScenarios":"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.","commonSituations":"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.","solutions":["Read the inner message after '转换PDF失败:' — it pinpoints the sub-failure","Verify LibreOffice works standalone: libreoffice --headless --convert-to pdf file.docx --outdir /tmp","Ensure pdf_path.parent exists (os.makedirs(pdf_path.parent, exist_ok=True)) before converting","Kill stale soffice processes (pkill soffice) that lock the headless profile, then retry","Check the docx opens in Word/LibreOffice GUI — corrupt inputs are a common cause"],"exampleFix":"// before\nos.system(f'libreoffice --headless --convert-to pdf \"{word_path}\" --outdir \"{pdf_path.parent}\"')\n\n// after\nimport subprocess\nos.makedirs(pdf_path.parent, exist_ok=True)\nresult = subprocess.run(['libreoffice','--headless','--convert-to','pdf',str(word_path),'--outdir',str(pdf_path.parent)], capture_output=True)\nif result.returncode != 0:\n    raise RuntimeError(f\"libreoffice failed: {result.stderr.decode()}\")","handlingStrategy":"try-catch","validationCode":"from pathlib import Path\nimport shutil, platform\n\ndef precheck(word_path, pdf_path):\n    p = Path(pdf_path if pdf_path else Path(word_path).with_suffix('.pdf'))\n    p.parent.mkdir(parents=True, exist_ok=True)\n    assert Path(word_path).exists()\n    if platform.system() == 'Linux':\n        assert shutil.which('libreoffice'), 'libreoffice missing'","typeGuard":null,"tryCatchPattern":"try:\n    out = WordToPdfConverter.convert_to_pdf(docx, pdf)\nexcept Exception as e:\n    msg = str(e)\n    if 'LibreOffice' in msg: install_or_skip()\n    elif 'No such file' in msg: fix_output_dir_and_retry()\n    else: raise","preventionTips":["Create the output directory before converting","Pre-validate that the docx opens (zipfile.is_zipfile) to catch corrupt inputs early","Use subprocess.run with arg lists instead of os.system string interpolation to survive odd paths"],"tags":["pdf-conversion","wrapper","libreoffice","file-io"],"backgroundTag":null,"analyzedSha":"d6bde0fa54373309bd05823a49bda8da019d2c77","analyzedAt":"2026-08-14T22:48:35.038Z","schemaVersion":2},"datasetVersion":"2026-08-15T17:31:12.345Z"}