{"record":{"id":"f273dc5aae18dbf1","repo":"binary-husky/gpt_academic","slug":"pdf-str-e-f273dc","errorCode":null,"errorMessage":"转换PDF失败: {str(e)}","messagePattern":"转换PDF失败: (.+?)","errorType":"exception","errorClass":"Exception","httpStatus":null,"severity":"error","filePath":"crazy_functions/review_fns/conversation_doc/word2pdf.py","lineNumber":65,"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":47,"sourceCodeEnd":83,"githubUrl":"https://github.com/binary-husky/gpt_academic/blob/d6bde0fa54373309bd05823a49bda8da019d2c77/crazy_functions/review_fns/conversation_doc/word2pdf.py#L47-L83","documentation":"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.","triggerScenarios":"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.","commonSituations":"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.","solutions":["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.","Ensure the output directory (pdf_path.parent) exists before calling convert_to_pdf (pdf_path.parent.mkdir(parents=True, exist_ok=True)).","Serialize concurrent conversions or give each call a separate HOME/-env:UserInstallation profile so headless libreoffice instances do not collide.","On Windows/macOS, install/repair MS Word — docx2pdf is only a COM/AppleScript bridge and cannot work without it.","Verify the input is a genuine .docx (zip with word/ inside) before conversion."],"exampleFix":"# before\nos.system(f'libreoffice --headless --convert-to pdf \"{word_path}\" --outdir \"{pdf_path.parent}\"')\ndefault_pdf = word_path.with_suffix('.pdf')\nif default_pdf != pdf_path:\n    os.rename(default_pdf, pdf_path)\n\n# after\ncode = subprocess.call(['libreoffice', '--headless', '--convert-to', 'pdf', str(word_path), '--outdir', str(pdf_path.parent)])\ndefault_pdf = word_path.with_suffix('.pdf')\nif not default_pdf.exists():\n    raise RuntimeError(f'libreoffice conversion failed with exit code {code}')\nif default_pdf != pdf_path:\n    pdf_path.parent.mkdir(parents=True, exist_ok=True)\n    os.replace(default_pdf, pdf_path)","handlingStrategy":"try-catch","validationCode":"from pathlib import Path\nimport zipfile\n\ndef is_valid_docx(p: str) -> bool:\n    p = Path(p)\n    return p.exists() and zipfile.is_zipfile(p) and 'word/' in zipfile.ZipFile(p).namelist()","typeGuard":null,"tryCatchPattern":"try:\n    out = WordToPdfConverter.convert_to_pdf(word, pdf)\nexcept Exception as e:\n    logger.error('pdf conversion failed: %s', e)  # str(e) embeds the real cause\n    # degrade: keep the .docx and notify the user instead of failing the whole job\n    return None","preventionTips":["Create pdf_path.parent before converting.","Run conversions sequentially or isolate each libreoffice call with its own user profile dir to avoid profile-lock failures.","Treat the embedded message as the diagnostic: it contains the original exception text."],"tags":["pdf-conversion","libreoffice","docx2pdf","error-wrapping","subprocess"],"backgroundTag":null,"analyzedSha":"d6bde0fa54373309bd05823a49bda8da019d2c77","analyzedAt":"2026-08-14T22:48:35.038Z","schemaVersion":2},"datasetVersion":"2026-08-15T17:31:12.345Z"}