# SPDX-FileCopyrightText: The Docling Contributors
# SPDX-License-Identifier: MIT
from __future__ import annotations
import logging
import os
import shutil
import signal
import subprocess
from collections.abc import Iterator
from contextlib import contextmanager
from io import BytesIO
from pathlib import Path
from tempfile import mkdtemp
from typing import TYPE_CHECKING, Callable, Final, Optional
from PIL import Image, ImageChops
if TYPE_CHECKING:
from docx.document import Document
# pypdfium2 ships with the PDF extras, not with format-docx/pptx/xlsx, but this
# module is imported eagerly by the Word, PowerPoint, and Excel backends. A
# module-level import therefore breaks those backends on installs that omit the
# PDF extras. Guard it here and report the absence once from
# `get_docx_to_pdf_converter`, which every caller goes through.
# See https://github.com/docling-project/docling/issues/3613.
_PYPDFIUM2_AVAILABLE: bool = False
try: # pragma: no cover - import-time guard
import pypdfium2
_PYPDFIUM2_AVAILABLE = True
except ImportError: # pragma: no cover - import-time guard
pass
_PYPDFIUM2_INSTALL_HINT = (
"The 'pypdfium2' package is required to rasterize the PDF that LibreOffice "
"produces, so charts and EMF/WMF pictures will be skipped. Install it with "
"`pip install 'docling-slim[format-pdf-pypdfium2]'`."
)
_log = logging.getLogger(__name__)
_pypdfium2_warning_emitted = False
LIBREOFFICE_TIMEOUT_S: Final[int] = 60
"""Maximum seconds to wait for a single LibreOffice conversion.
Without this, a hung ``soffice`` process (e.g. a modal dialog it can't
show in headless mode) blocks the calling thread forever.
"""
LIBREOFFICE_HARDENING_FLAGS: Final[tuple[str, ...]] = (
"--headless",
"--norestore",
"--nologo",
"--nolockcheck",
"--nodefault",
)
"""Flags that constrain a throwaway ``soffice`` invocation.
``--headless`` avoids any GUI/dialogs; ``--norestore`` stops LibreOffice
from trying to reopen documents from a previous crashed session (which can
include attacker files); ``--nologo``/``--nodefault`` suppress the start
splash and the empty default document; ``--nolockcheck`` avoids stalling on
a stale lock file inside the throwaway profile.
"""
def _registrymodifications_xcu() -> str:
"""Return the contents of a hardening ``registrymodifications.xcu``.
The file is seeded into the throwaway user profile so that the very
first (and only) ``soffice`` launch already runs with a locked-down
configuration instead of relying on the build's implicit defaults:
* ``MacroSecurityLevel = 3`` (Very High / maximum) and
``DisableMacrosExecution = true`` prevent document macros from
running during conversion.
* ``.../Writer/Content/Update/Link = 0`` and the Calc equivalent set
"update links when loading" to *never*, so opening an attacker file
does not fetch external/DDE-linked content (an SSRF / file-inclusion
vector via e.g. ``TargetMode="External"`` relationships).
Registry nodes for DDE, OLE-object, and remote-image resolution are
*not* set here because no single well-documented key covers those
vectors across LibreOffice versions.
"""
return (
'\n'
"\n'
' - \n'
' \n'
" 3\n"
" \n"
"
\n"
' - \n'
' \n'
" true\n"
" \n"
"
\n"
' - \n'
' \n'
" 0\n"
" \n"
"
\n"
' - \n'
' \n'
" 0\n"
" \n"
"
\n"
"\n"
)
def _build_soffice_command(
libreoffice_cmd: str,
profile_arg: str,
*,
target_format: str,
outdir: str,
input_path: str,
) -> list[str]:
"""Assemble a hardened ``soffice`` argv for a single conversion.
Kept as a pure function so the exact flags can be asserted in unit
tests without a LibreOffice binary present.
"""
return [
libreoffice_cmd,
profile_arg,
*LIBREOFFICE_HARDENING_FLAGS,
"--convert-to",
target_format,
"--outdir",
outdir,
str(input_path),
]
def _kill_soffice_process_group(proc: subprocess.Popen) -> None:
"""Best-effort SIGKILL of the whole ``soffice`` process group.
``soffice`` is a thin wrapper that forks ``soffice.bin``; killing only
the wrapper (as ``subprocess.run(timeout=...)`` does) can leave the real
worker alive to accumulate. Launching with ``start_new_session=True``
puts the wrapper in its own process group so the whole tree can be
signalled here.
"""
if hasattr(os, "killpg") and hasattr(os, "getpgid"):
try:
os.killpg(os.getpgid(proc.pid), signal.SIGKILL)
except (ProcessLookupError, PermissionError, OSError):
proc.kill()
else: # pragma: no cover - Windows has no process groups
proc.kill()
try:
proc.wait(timeout=5)
except Exception:
pass
def _run_hardened_soffice(args: list[str], timeout_s: int) -> None:
"""Run ``soffice`` in its own process group with a hard timeout.
On timeout, the entire process group is killed so ``soffice.bin``
cannot survive.
Args:
args: The ``soffice`` command line to execute.
timeout_s: Timeout in seconds for the subprocess.
Raises:
subprocess.CalledProcessError: If ``soffice`` exits with a non-zero
status.
subprocess.TimeoutExpired: If ``soffice`` does not exit within
``timeout_s`` seconds.
"""
proc = subprocess.Popen(
args,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
start_new_session=True,
)
try:
returncode = proc.wait(timeout=timeout_s)
except subprocess.TimeoutExpired:
_kill_soffice_process_group(proc)
raise
if returncode != 0:
raise subprocess.CalledProcessError(returncode, args)
def get_libreoffice_cmd(raise_if_unavailable: bool = False) -> Optional[str]:
"""Return the libreoffice cmd and optionally test it."""
libreoffice_cmd = (
os.environ.get("DOCLING_LIBREOFFICE_CMD")
or shutil.which("libreoffice")
or shutil.which("soffice")
or (
"/Applications/LibreOffice.app/Contents/MacOS/soffice"
if os.path.isfile("/Applications/LibreOffice.app/Contents/MacOS/soffice")
else None
)
)
if raise_if_unavailable:
if libreoffice_cmd is None:
raise RuntimeError("Libreoffice not found")
# The following test will raise if the libreoffice_cmd cannot be used
subprocess.run(
[
libreoffice_cmd,
"-h",
],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
check=True,
)
return libreoffice_cmd
@contextmanager
def _isolated_libreoffice_profile() -> Iterator[str]:
"""Yield a ``-env:UserInstallation`` argument backed by a throwaway profile.
LibreOffice takes an exclusive lock on its user profile directory.
Without this, concurrent conversions (parallel workers, docling-serve
handling simultaneous requests) share the default profile and collide
on that lock, causing conversions to fail intermittently and silently.
The profile is also seeded with a hardening ``registrymodifications.xcu``
(see `_registrymodifications_xcu`) so the conversion runs with
macros disabled and external link updates turned off.
Yields:
A ``-env:UserInstallation=`` CLI argument pointing at a freshly
created profile directory that contains only the hardening
``registrymodifications.xcu``. The directory is removed again
once the ``with`` block exits.
"""
profile_dir = Path(mkdtemp(prefix="docling_lo_profile_"))
try:
user_dir = profile_dir / "user"
user_dir.mkdir(parents=True, exist_ok=True)
(user_dir / "registrymodifications.xcu").write_text(
_registrymodifications_xcu(), encoding="utf-8"
)
yield f"-env:UserInstallation={profile_dir.as_uri()}"
finally:
shutil.rmtree(profile_dir, ignore_errors=True)
def convert_to_modern_format(
source: BytesIO | Path,
source_suffix: str,
target_suffix: str,
timeout_s: int = 120,
) -> BytesIO:
"""Convert a legacy binary Office file to modern Open XML format via LibreOffice.
Both file paths and in-memory streams are accepted. When a ``BytesIO`` is
supplied the bytes are written to a temporary file (named with
``source_suffix`` so LibreOffice can detect the format) before invoking the
CLI; the temporary file is removed together with the rest of the temp
directory once the conversion finishes.
Args:
source: Path to the source file, or a ``BytesIO`` with its contents.
source_suffix: File extension of the source format without leading dot
(e.g. ``"doc"``, ``"xls"``, ``"ppt"``). Required when *source* is
a ``BytesIO`` so the temp file gets the right name; ignored for
``Path`` inputs (the path's own suffix is used instead).
target_suffix: Target extension without leading dot (``"docx"``,
``"xlsx"``, or ``"pptx"``).
timeout_s: Timeout in seconds for the LibreOffice subprocess.
Returns:
A ``BytesIO`` buffer with the converted file contents.
Raises:
RuntimeError: When LibreOffice is not installed, the subprocess fails,
or the expected output file is not produced.
"""
libreoffice_cmd = get_libreoffice_cmd()
if libreoffice_cmd is None:
raise RuntimeError(
f"LibreOffice is required to convert a .{source_suffix} file to "
f".{target_suffix}. Install LibreOffice and make sure it is on PATH."
)
tmp_dir = Path(mkdtemp())
try:
if isinstance(source, BytesIO):
source.seek(0)
input_path = tmp_dir / f"input.{source_suffix}"
input_path.write_bytes(source.read())
else:
input_path = source
with _isolated_libreoffice_profile() as profile_arg:
_run_hardened_soffice(
_build_soffice_command(
libreoffice_cmd,
profile_arg,
target_format=target_suffix,
outdir=str(tmp_dir),
input_path=str(input_path),
),
timeout_s=timeout_s,
)
converted_path = tmp_dir / (input_path.stem + "." + target_suffix)
if not converted_path.exists():
raise RuntimeError(
f"LibreOffice did not produce the expected output: {converted_path}"
)
return BytesIO(converted_path.read_bytes())
finally:
shutil.rmtree(tmp_dir, ignore_errors=True)
def get_docx_to_pdf_converter() -> Optional[Callable]:
"""
Detects the best available DOCX to PDF tool and returns a conversion function.
The returned function accepts (input_path, output_path).
Returns None if no tool is available, or if pypdfium2 is missing: every caller
rasterizes the resulting PDF with it, so the conversion would be useless.
"""
# Every consumer feeds the LibreOffice PDF straight into pypdfium2, so report
# the missing package here once rather than in each backend.
global _pypdfium2_warning_emitted
if not _PYPDFIUM2_AVAILABLE:
if not _pypdfium2_warning_emitted:
_log.warning(_PYPDFIUM2_INSTALL_HINT)
_pypdfium2_warning_emitted = True
return None
# Try LibreOffice
libreoffice_cmd = get_libreoffice_cmd()
if libreoffice_cmd:
def convert_with_libreoffice(
input_path: str | Path, output_path: str | Path
) -> None:
"""Convert a DOCX/PPTX file to PDF via LibreOffice.
Runs the conversion in its own throwaway LibreOffice profile
(see ``_isolated_libreoffice_profile``) with a bounded timeout,
so a hung ``soffice`` process cannot block the calling thread
forever and concurrent conversions cannot collide on the
default profile lock.
Args:
input_path: Path to the source file to convert.
output_path: Desired path for the converted PDF.
"""
with _isolated_libreoffice_profile() as profile_arg:
_run_hardened_soffice(
_build_soffice_command(
libreoffice_cmd,
profile_arg,
target_format="pdf",
outdir=os.path.dirname(output_path),
input_path=str(input_path),
),
timeout_s=LIBREOFFICE_TIMEOUT_S,
)
expected_output = os.path.join(
os.path.dirname(output_path),
os.path.splitext(os.path.basename(input_path))[0] + ".pdf",
)
if expected_output != output_path:
os.rename(expected_output, output_path)
return convert_with_libreoffice
## Space for other DOCX to PDF converters if available
# No tools found
return None
def crop_whitespace(image: Image.Image, bg_color=None, padding=0) -> Image.Image:
if bg_color is None:
bg_color = image.getpixel((0, 0))
bg = Image.new(image.mode, image.size, bg_color)
diff = ImageChops.difference(image, bg)
bbox = diff.getbbox()
if bbox:
left, upper, right, lower = bbox
left = max(0, left - padding)
upper = max(0, upper - padding)
right = min(image.width, right + padding)
lower = min(image.height, lower + padding)
return image.crop((left, upper, right, lower))
else:
return image
def get_pil_from_dml_docx(
docx: Document, converter: Optional[Callable]
) -> Optional[Image.Image]:
if converter is None:
return None
temp_dir = Path(mkdtemp())
try:
temp_docx = Path(temp_dir / "drawing_only.docx")
temp_pdf = Path(temp_dir / "drawing_only.pdf")
# 1) Save docx temporarily
docx.save(str(temp_docx))
# 2) Export to PDF
converter(temp_docx, temp_pdf)
# 3) Load PDF as PNG
pdf = pypdfium2.PdfDocument(temp_pdf)
page = pdf[0]
image = crop_whitespace(page.render(scale=2).to_pil())
page.close()
pdf.close()
finally:
shutil.rmtree(temp_dir, ignore_errors=True)
return image