### pyoffice_demo main function Source: https://github.com/begonia-org/pylibreoffice Minimal C++ usage example of office::Office, compiled from src/main.cxx and installed to bin/ by CMake. It drives office::Office directly with hardcoded input/output paths and does not take command-line arguments. ```cpp int main(int argc, char *argv[]) { office::Office office("/usr/lib/libreoffice/program"); office.saveAs("/data/work/office-converter/tests/data/en.doc", "/data/work/office-converter/tests/data/test_en.pdf", "pdf"); office.saveAs("/data/work/office-converter/tests/data/test.xls", "/data/work/office-converter/tests/data/test_xls_cpp.pdf", "pdf"); return 0; } ``` -------------------------------- ### Install Chinese fonts for document conversion Source: https://github.com/begonia-org/pylibreoffice/blob/master/README.md Install Chinese fonts and locale settings on Ubuntu to ensure proper rendering of Chinese characters in converted documents. ```bash sudo apt-get install -y fonts-wqy-zenhei fonts-wqy-microhei xfonts-intl-chinese ttf-wqy-zenhei ttf-wqy-microhei language-pack-zh-hans language-pack-zh-hant && \ sudo dpkg-reconfigure locales && \ sudo update-locale LANG=zh_CN.UTF-8 ``` -------------------------------- ### Convert DOC and XLS files to PDF Source: https://github.com/begonia-org/pylibreoffice/blob/master/README.md Example usage of PyOffice to convert .doc and .xls files to PDF. The save_as method takes input path, output path, and format ('pdf'). ```python from pylibreoffice.core import PyOffice class Example: def __init__(self): self.office = PyOffice("/usr/lib/libreoffice/program/") def doc(self): # Convert the doc file to pdf print(self.office.save_as("./test.doc", "./test.pdf", "pdf")) def xls(self): # Convert the xls file to pdf print(self.office.save_as("./test.xls", "./test_xls.pdf", "pdf")) if __name__ == '__main__': ex = Example() ex.xls() ex.doc() ``` -------------------------------- ### Install pylibreoffice via pip Source: https://github.com/begonia-org/pylibreoffice/blob/master/README.md Install the pylibreoffice Python package using pip. ```bash pip install pylibreoffice ``` -------------------------------- ### Office constructor Source: https://github.com/begonia-org/pylibreoffice Creates a new Office instance pointing to the LibreOffice installation directory. The bin_dir can be passed as a positional or keyword argument. ```APIDOC ## Office constructor ### Description Creates a new Office instance pointing to the LibreOffice installation directory. The bin_dir can be passed as a positional or keyword argument. ### Method Office ### Parameters #### Arguments - **bin_dir** (string) - Required - Path to the LibreOffice program directory (e.g., "/usr/lib/libreoffice/program") ### Response Returns an Office instance. ### Request Example ```python import pylibreoffice.pybind11_office as pybind_office # Positional argument office = pybind_office.Office("/usr/lib/libreoffice/program") # Keyword argument office = pybind_office.Office(bin_dir="/usr/lib/libreoffice/program/") ``` ``` -------------------------------- ### PyOffice(libreoffice_dir, bridge) Source: https://github.com/begonia-org/pylibreoffice Constructs a PyOffice instance, selecting the pybind11 or Cython bridge based on the bridge parameter. The libreoffice_dir must point to a valid LibreOffice installation directory. ```APIDOC ## PyOffice(libreoffice_dir, bridge) ### Description Constructs a PyOffice instance, selecting the pybind11 or Cython bridge based on the bridge parameter. The libreoffice_dir must point to a valid LibreOffice installation directory. ### Method Constructor ### Signature ```python def __init__(self, libreoffice_dir="/usr/lib/libreoffice/program", bridge="pybind11"): ``` ### Parameters - `libreoffice_dir` (str) - Optional - Default: `"/usr/lib/libreoffice/program"` - Directory containing the LibreOffice binaries/libraries, passed to `lok::lok_cpp_init` via the selected bridge. Must be a valid LibreOffice install directory (e.g. `/usr/lib/libreoffice/program/` on Debian/Ubuntu). - `bridge` (str) - Optional - Default: `"pybind11"` - Backend selector. Exactly `"pybind11"` uses `pylibreoffice.pybind11_office.Office`; any other value uses `pylibreoffice.py_office.CyOffice` (Cython). ### Return A `PyOffice` instance. The selected bridge instance is stored in the private attribute `__office` (name-mangled to `_PyOffice__office`). ### Behavior Notes - `pylibreoffice/core.py` imports both bridge modules unconditionally at module import time (`pylibreoffice.py_office` and `pylibreoffice.pybind11_office`). Both compiled extension modules must be importable for `import pylibreoffice.core` to succeed. - An invalid `libreoffice_dir` is not validated at construction; validation/degradation behavior depends on `lok::lok_cpp_init` (see [office::Office](Office-cpp.md)). ``` -------------------------------- ### Install LibreOffice dependencies Source: https://github.com/begonia-org/pylibreoffice/blob/master/README.md Install LibreOffice and development packages required by pylibreoffice. Requires Python 3.10+ and LibreOffice 7.2+. ```bash sudo apt-get install -y libreoffice libreoffice-dev libreoffice-dev-doc ``` -------------------------------- ### C++ usage with office::Office Source: https://github.com/begonia-org/pylibreoffice Standalone C++ example similar to pyoffice_demo. It includes office.hpp, creates an office::Office instance, and calls saveAs. If saveAs returns false, either documentLoad failed or lok::Document::saveAs failed, and the program returns 1. ```cpp #include "office.hpp" int main() { office::Office office("/usr/lib/libreoffice/program"); if (!office.saveAs("report.doc", "report.pdf", "pdf")) { // either documentLoad failed or lok::Document::saveAs failed return 1; } office.release(); return 0; } ``` -------------------------------- ### office::Office constructor (C++) Source: https://github.com/begonia-org/pylibreoffice Initializes the C++ Office object with the required bin_dir parameter. ```APIDOC ## office::Office constructor (C++) ### Description Initializes the C++ Office object with the required bin_dir parameter. ### Method Constructor ### Parameters #### Constructor Parameters - `bin_dir` (const std::string&) - Required - Passed to `lok::lok_cpp_init`. ``` -------------------------------- ### PyOffice constructor Source: https://github.com/begonia-org/pylibreoffice Initializes the PyOffice object with optional LibreOffice directory and bridge backend. ```APIDOC ## PyOffice constructor ### Description Initializes the PyOffice object with optional LibreOffice directory and bridge backend. ### Method Constructor ### Parameters #### Constructor Parameters - `libreoffice_dir` (str) - Optional - Path to the LibreOffice program/binaries directory, forwarded to the bridge constructor and ultimately to `lok::lok_cpp_init`. Default: `"/usr/lib/libreoffice/program"`. - `bridge` (str) - Optional - Backend selector. Literal `"pybind11"` → `pylibreoffice.pybind11_office.Office`; any other value → `pylibreoffice.py_office.CyOffice` (Cython). Default: `"pybind11"`. ``` -------------------------------- ### CyOffice constructor Source: https://github.com/begonia-org/pylibreoffice Initializes the CyOffice object with optional LibreOffice directory. ```APIDOC ## CyOffice constructor ### Description Initializes the CyOffice object with optional LibreOffice directory. ### Method Constructor ### Parameters #### Constructor Parameters - `libreoffice_dir` (str) - Optional - Path to the LibreOffice program/binaries directory, passed to `new Office(libreoffice_dir)`. Default: `"/usr/lib/libreoffice/program"`. ``` -------------------------------- ### Office constructor (pybind11) Source: https://github.com/begonia-org/pylibreoffice Initializes the pybind11 Office object with the required bin_dir parameter. ```APIDOC ## Office constructor (pybind11) ### Description Initializes the pybind11 Office object with the required bin_dir parameter. ### Method Constructor ### Parameters #### Constructor Parameters - `bin_dir` (str) - Required - Same meaning as `libreoffice_dir`; keyword name is `bin_dir`. ``` -------------------------------- ### save_as(src, dest, fmt="pdf") -> bool Source: https://github.com/begonia-org/pylibreoffice Converts a Microsoft Office document to a specified output format using LibreOffice. Returns True on success, False if the input could not be loaded or the conversion failed. ```APIDOC ## save_as(src, dest, fmt="pdf") -> bool ### Description Converts a Microsoft Office document (e.g., .doc, .docx, .xls, .xlsx, .ppt, .pptx) to a specified output format using LibreOffice. Returns True if the conversion succeeded, False if the input could not be loaded or the save failed. ### Method save_as ### Signature ```python def save_as(self, src: str, dest: str, fmt: str = "pdf") -> bool: ``` ### Parameters - **src** (str) - Required - Path to the input Microsoft Office document. Must be readable by LibreOffice. - **dest** (str) - Required - Path of the output file to write. - **fmt** (str) - Optional, default `"pdf"` - Target output format identifier, passed to LibreOfficeKit as the filter/format string. ### Return Value - **bool** - `True` if the underlying LibreOfficeKit `saveAs` reported success; `False` if the input document could not be loaded or the save failed. The destination file may be absent or partially written when `False` is returned. ### Throws No exceptions are defined. Failure is signaled only by the `False` return value. If the underlying native call dereferences a released/invalid handle, behavior is undefined. ### Delegation Calls `self.__office.save_as(src, dest, fmt)`. Argument names on the bridge differ per backend (`input_file`, `output_file`, `format`/`out_format`), but positions match. ``` -------------------------------- ### Basic usage: convert .doc and .xls to PDF Source: https://github.com/begonia-org/pylibreoffice Creates a PyOffice instance with the LibreOffice program directory and converts documents to PDF using save_as. The bridge defaults to 'pybind11' and the format defaults to 'pdf' when omitted. ```python from pylibreoffice.core import PyOffice office = PyOffice("/usr/lib/libreoffice/program/") # bridge defaults to "pybind11" ok1 = office.save_as("./test.doc", "./test.pdf", "pdf") print(f"doc -> pdf: {ok1}") ok2 = office.save_as("./test.xls", "./test_xls.pdf") print(f"xls -> pdf: {ok2}") # fmt omitted, defaults to "pdf" ``` -------------------------------- ### save_as(src, dest, fmt) Source: https://github.com/begonia-org/pylibreoffice Converts a document from a source file to a destination file in the specified format, defaulting to PDF. This method forwards the call to the selected bridge's save_as method. ```APIDOC ## save_as(src, dest, fmt) ### Description Converts a document from a source file to a destination file in the specified format, defaulting to PDF. This method forwards the call to the selected bridge's save_as method. ### Method save_as ### Signature ```python def save_as(self, src: str, dest: str, fmt: str = "pdf") -> bool: ``` ### Parameters - `src` (str) - Required - Source file path. - `dest` (str) - Required - Destination file path. - `fmt` (str) - Optional - Default: `"pdf"` - Output format. ### Return `bool` - Returns `True` on success, `False` on failure. ``` -------------------------------- ### Office.save_as (pybind11) Source: https://github.com/begonia-org/pylibreoffice Saves the document with the specified input file, output file, and format. ```APIDOC ## Office.save_as (pybind11) ### Description Saves the document with the specified input file, output file, and format. ### Method save_as ### Parameters #### Method Parameters - `input_file` (str) - Required - Input file path. - `output_file` (str) - Required - Output file path. - `format` (str) - Required - Output format identifier. No default on this bridge. ``` -------------------------------- ### Office(bin_dir) Source: https://github.com/begonia-org/pylibreoffice Constructor for the Office class. Initializes an Office instance with the LibreOffice binary directory. ```APIDOC ## Office(bin_dir) ### Description Constructor for the Office class. Initializes an Office instance with the LibreOffice binary directory. ### Parameters - `bin_dir` (str) - Required - Directory of the LibreOffice installation. Passed to `office::Office`, which forwards it to `lok::lok_cpp_init`. ### Return An `Office` instance owning a C++ `office::Office`. ``` -------------------------------- ### Basic usage: save_as with positional arguments Source: https://github.com/begonia-org/pylibreoffice Creates an Office instance pointing to the LibreOffice program directory and converts a .doc file to PDF using save_as. Prints the boolean result of the conversion. ```python import pylibreoffice.pybind11_office as pybind_office office = pybind_office.Office("/usr/lib/libreoffice/program") ok = office.save_as("./test.doc", "./test.pdf", "pdf") print(f"doc -> pdf: {ok}") ``` -------------------------------- ### Office constructor initializes lok::Office Source: https://github.com/begonia-org/pylibreoffice Constructor calls lok::lok_cpp_init with bin_dir and stores the result. Several setOption calls are commented out, so no options are configured. ```cpp Office::Office(const std::string &bin_dir) { office = lok::lok_cpp_init(bin_dir.c_str()); // 设置选项 // office->setOption("EmbedStandardFonts", "true"); // office->setOption("PrintArea", "A1:Z50"); // office->setOption("ReduceImageResolution", "false"); // office->setOption("UseLosslessCompression", "true"); // office->setOption("headless", "true"); // office->setOption("nocrashreport", "true"); } ``` -------------------------------- ### PyOffice.save_as Source: https://github.com/begonia-org/pylibreoffice Saves the document in the specified output format. ```APIDOC ## PyOffice.save_as ### Description Saves the document in the specified output format. ### Method save_as ### Parameters #### Method Parameters - `fmt` (str) - Optional - Output format identifier forwarded to the bridge. Default: `"pdf"`. ``` -------------------------------- ### Office constructor call with bin_dir Source: https://github.com/begonia-org/pylibreoffice Shows the Python call signature for the `Office` constructor. The `bin_dir` parameter is required and must be a string; there is no default value. ```python Office(bin_dir) # py::init, keyword name "bin_dir" ``` -------------------------------- ### Keyword arguments: save_as with named parameters Source: https://github.com/begonia-org/pylibreoffice Uses keyword arguments for bin_dir and save_as. The conversion result is a boolean; failure does not raise an exception, so check the return value. Calls office.release() to free resources. ```python import pylibreoffice.pybind11_office as pybind_office office = pybind_office.Office(bin_dir="/usr/lib/libreoffice/program/") ok = office.save_as(input_file="test.xls", output_file="test_xls.pdf", format="pdf") if not ok: print("conversion failed — no exception is raised; check the boolean") office.release() ``` -------------------------------- ### Basic usage: save_as with explicit format Source: https://github.com/begonia-org/pylibreoffice Creates a CyOffice instance with the LibreOffice program path and converts a file to PDF using the save_as method with an explicit output format. ```python from pylibreoffice.py_office import CyOffice office = CyOffice("/usr/lib/libreoffice/program") ok = office.save_as("./test.xls", "./test_xls.pdf", "pdf") print(f"converted: {ok}") ``` -------------------------------- ### save_as(input_file, output_file, out_format="pdf") -> bool Source: https://github.com/begonia-org/pylibreoffice Converts a source document to a specified output format using LibreOfficeKit. Returns True on success, False on failure. ```APIDOC ## save_as(input_file, output_file, out_format="pdf") -> bool ### Description Converts a source document to a specified output format using LibreOfficeKit. Returns True on success, False on failure. ### Method save_as ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - `input_file` (str) - Required - Path of the source document to convert. - `output_file` (str) - Required - Path of the destination file to write. - `out_format` (str) - Optional - Output format identifier passed to the C++ `saveAs` (e.g. `"pdf"`). Default: `"pdf"`. ### Response #### Success Response (200) - `bool` - The result of `office->saveAs(...)`, i.e. `True` when the LibreOfficeKit conversion reported success, `False` when the document could not be loaded or the save failed. ### Notes - The source raises no Python exceptions. Note the C++ pointer is NOT null-checked on the way to `saveAs` — calling `save_as` after `release()` (or after a failed `lok_cpp_init`) dereferences a NULL `office` pointer and results in undefined behavior (likely a crash). ``` -------------------------------- ### save_as(input_file, output_file, format) -> bool Source: https://github.com/begonia-org/pylibreoffice Converts a source document to the specified output format. Returns True on success, False if the document could not be loaded or saved. ```APIDOC ## save_as(input_file, output_file, format) -> bool ### Description Converts a source document to the specified output format. Returns True on success, False if the document could not be loaded or saved. ### Method Function call ### Endpoint `Office.save_as(input_file, output_file, format)` ### Parameters #### Arguments - **input_file** (str) - Required - Path of the source document to convert. - **output_file** (str) - Required - Path of the destination file to write. - **format** (str) - Required - Output format identifier (e.g. `"pdf"`). Unlike `CyOffice`, **there is no default** — passing fewer than three arguments raises a `TypeError` from pybind11. ### Response #### Success Response - **bool** - `True` on success, `False` if `documentLoad` returned a null `lok::Document` or `lok::Document::saveAs` failed. ### Throws - **TypeError** - Raised for wrong argument count/types. ### Notes - If `save_as` is called after `release()`, the C++ code dereferences a NULL `lok::Office*` (undefined behavior). - Docstring: `"Save the input file to the specified output format"`. ``` -------------------------------- ### Error handling: checking boolean result instead of exceptions Source: https://github.com/begonia-org/pylibreoffice Uses the default LibreOffice program directory and checks the boolean return of save_as to detect failures. No exception is raised on failure; the bool indicates whether the document failed to load or the save step failed. ```python from pylibreoffice.core import PyOffice office = PyOffice() # default LibreOffice program directory src = "./missing.doc" dest = "./missing.pdf" result = office.save_as(src, dest, "pdf") if not result: # No exception is raised on failure — the bool tells you the # document failed to load or the save step failed. print(f"conversion failed for {src}; {dest} may not exist or be incomplete") else: print(f"converted {src} -> {dest}") ``` -------------------------------- ### Using the default format Source: https://github.com/begonia-org/pylibreoffice Uses the default LibreOffice path and default output format 'pdf' when calling save_as without specifying a format. ```python from pylibreoffice.py_office import CyOffice office = CyOffice() # defaults to "/usr/lib/libreoffice/program" print(office.save_as("./test.doc", "./test.pdf")) # out_format defaults to "pdf" ``` -------------------------------- ### release() Source: https://github.com/begonia-org/pylibreoffice Releases the underlying LibreOfficeKit office handle. Takes no arguments and returns None. ```APIDOC ## release() ### Description Releases the underlying LibreOfficeKit office handle. Takes no arguments and returns None. ### Method release ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Response #### Success Response (200) - None (returns `None`) ### Notes - Invokes `office::Office::release()`, which deletes the underlying `lok::Office` and sets the C++ member pointer to NULL. After this call, the `lok::Office` handle is gone, but `CyOffice`'s own pointer field still points at the C++ `office::Office` object itself (which remains valid), so `save_as` afterwards is unsafe. ``` -------------------------------- ### pybind11 module definition for Office class Source: https://github.com/begonia-org/pylibreoffice Defines the pybind11 module `pybind11_office` binding the C++ class `office::Office`. Exposes the constructor with keyword `bin_dir`, the `save_as` method with keywords `input_file`, `output_file`, `format`, and the `release` method. No parameter defaults are set; all arguments are required. ```cpp #include #include // 支持 STL 容器,如 std::string #include "office.hpp" namespace py = pybind11; PYBIND11_MODULE(pybind11_office, m) { m.doc() = "Pybind11 bindings for Office class"; // 绑定 office::Office 类 py::class_(m, "Office") .def(py::init(), py::arg("bin_dir"), "Initialize the Office instance with LibreOffice binary directory") .def("save_as", &office::Office::saveAs, py::arg("input_file"), py::arg("output_file"), py::arg("format"), "Save the input file to the specified output format") .def("release", &office::Office::release, "Release resources"); } ``` -------------------------------- ### CyOffice.save_as Source: https://github.com/begonia-org/pylibreoffice Saves the document in the specified output format. ```APIDOC ## CyOffice.save_as ### Description Saves the document in the specified output format. ### Method save_as ### Parameters #### Method Parameters - `out_format` (str) - Optional - Output format identifier; passed to C++ `saveAs`. Default: `"pdf"`. ``` -------------------------------- ### bool saveAs(const std::string &input_file, const std::string& output_file, const std::string& format) Source: https://github.com/begonia-org/pylibreoffice Converts a document from one format to another using LibreOfficeKit. Loads the input document and saves it to the output path with the specified format, returning success or failure. ```APIDOC ## bool saveAs(const std::string &input_file, const std::string& output_file, const std::string& format) ### Description Converts a document from one format to another using LibreOfficeKit. Loads the input document and saves it to the output path with the specified format, returning success or failure. ### Method C++ method ### Endpoint `Office::saveAs` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - `input_file` (const std::string&) - Required - Source document path, passed to `lok::Office::documentLoad(input_file.c_str(), nullptr)`. - `output_file` (const std::string&) - Required - Destination path, passed as the `pUrl` of `lok::Document::saveAs`. - `format` (const std::string&) - Required - Output format identifier, passed as the `pFormat` of `lok::Document::saveAs` (e.g. `"pdf"`). ### Response #### Success Response (200) - `bool` - Returns `false` if `documentLoad` returns a null `lok::Document` (unreadable/unknown document). Otherwise returns the value of `lok::Document::saveAs` — `true` on success, `false` on failure. ### Request Example ```cpp bool Office::saveAs(const std::string &input_file, const std::string &output_file, const std::string &format) { lok::Document *document = office->documentLoad(input_file.c_str(), nullptr); if (!document) { return false; } bool ret = document->saveAs(output_file.c_str(), format.c_str(), nullptr); delete document; document = nullptr; return ret; } ``` #### Response Example No response example provided in the source. ``` -------------------------------- ### Office.save_as Source: https://github.com/begonia-org/pylibreoffice Converts a document from one format to another using LibreOffice. The method returns a boolean indicating success or failure, and requires a format argument to be explicitly provided. ```APIDOC ## Office.save_as ### Description Converts a document from one format to another using LibreOffice. The method returns a boolean indicating success or failure, and requires a format argument to be explicitly provided. ### Method save_as ### Parameters #### Arguments - **input_file** (string) - Required - Path to the input document file - **output_file** (string) - Required - Path where the converted document will be saved - **format** (string) - Required - Target format for conversion (e.g., "pdf") ### Response #### Success Response - **bool** (boolean) - Returns `True` if conversion succeeded, `False` if it failed ### Request Example ```python import pylibreoffice.pybind11_office as pybind_office office = pybind_office.Office("/usr/lib/libreoffice/program") ok = office.save_as("./test.doc", "./test.pdf", "pdf") print(f"doc -> pdf: {ok}") ``` ### Request Example (Keyword Arguments) ```python import pylibreoffice.pybind11_office as pybind_office office = pybind_office.Office(bin_dir="/usr/lib/libreoffice/program/") ok = office.save_as(input_file="test.xls", output_file="test_xls.pdf", format="pdf") if not ok: print("conversion failed — no exception is raised; check the boolean") office.release() ``` ### Error Handling If the `format` argument is missing, a `TypeError` is raised: ```python import pylibreoffice.pybind11_office as pybind_office office = pybind_office.Office("/usr/lib/libreoffice/program") try: office.save_as("test.doc", "test.pdf") # format is MISSING except TypeError as exc: # pybind11: save_as() missing required argument: 'format' print("format argument is required on this bridge:", exc) ``` ``` -------------------------------- ### release() Source: https://github.com/begonia-org/pylibreoffice Releases resources held by the Office instance. ```APIDOC ## release() ### Description Releases resources held by the Office instance. ``` -------------------------------- ### CyOffice __cinit__ signature Source: https://github.com/begonia-org/pylibreoffice Constructor signature for CyOffice with default libreoffice_dir parameter. The parameter is Cython-typed as str and defaults to "/usr/lib/libreoffice/program". ```cython def __cinit__(self, str libreoffice_dir="/usr/lib/libreoffice/program"): ``` -------------------------------- ### Explicit teardown with release() Source: https://github.com/begonia-org/pylibreoffice Calls release() to delete the underlying lok::Office handle. Do not call save_as() after release() because the source does not guard against a NULL pointer, leading to undefined behavior. ```python from pylibreoffice.py_office import CyOffice office = CyOffice() ok = office.save_as("a.docx", "a.pdf") office.release() # deletes the underlying lok::Office handle # NOTE: do not call save_as() after release() — the source does not guard # against a NULL lok::Office pointer, so this is undefined behavior. ``` -------------------------------- ### saveAs method implementation Source: https://github.com/begonia-org/pylibreoffice Saves a document from input_file to output_file in the specified format. Returns false if documentLoad fails, otherwise returns the result of lok::Document::saveAs. Deletes the document after use. Note: if office is NULL, this dereferences a null pointer and crashes. ```cpp bool Office::saveAs(const std::string &input_file, const std::string &output_file, const std::string &format) { lok::Document *document = office->documentLoad(input_file.c_str(), nullptr); if (!document) { return false; } bool ret = document->saveAs(output_file.c_str(), format.c_str(), nullptr); delete document; document = nullptr; return ret; } ``` -------------------------------- ### PyOffice constructor signature Source: https://github.com/begonia-org/pylibreoffice The constructor signature for PyOffice. The bridge parameter is compared with ==; any value other than 'pybind11' selects the Cython bridge. ```python def __init__(self, libreoffice_dir="/usr/lib/libreoffice/program", bridge="pybind11"): ``` -------------------------------- ### PyOffice class definition Source: https://github.com/begonia-org/pylibreoffice The full PyOffice class from pylibreoffice/core.py. It selects a bridge at construction and forwards save_as calls with a 'pdf' default. ```python class PyOffice: def __init__(self, libreoffice_dir="/usr/lib/libreoffice/program", bridge="pybind11"): if bridge == "pybind11": self.__office = _pybind11_office.Office(libreoffice_dir) else: self.__office = CyOffice(libreoffice_dir) def save_as(self, src: str, dest: str, fmt: str = "pdf") -> bool: return self.__office.save_as(src, dest, fmt) ``` -------------------------------- ### bool release() Source: https://github.com/begonia-org/pylibreoffice Releases the underlying LibreOfficeKit handle and marks the Office object as unusable. Always returns true. ```APIDOC ## bool release() ### Description Releases the underlying LibreOfficeKit handle and marks the Office object as unusable. Always returns true. ### Method C++ method ### Endpoint `Office::release` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Response #### Success Response (200) - `bool` - Always `true`. ### Request Example ```cpp bool Office::release() { if (office){ delete office; } office = nullptr; return true; } ``` #### Response Example No response example provided in the source. ``` -------------------------------- ### release() Source: https://github.com/begonia-org/pylibreoffice Deletes the underlying lok::Office handle. After calling release(), do not call save_as() again as it is undefined behavior. ```APIDOC ## release() ### Description Deletes the underlying lok::Office handle. After calling release(), do not call save_as() again as it is undefined behavior. ### Example ```python from pylibreoffice.py_office import CyOffice office = CyOffice() ok = office.save_as("a.docx", "a.pdf") office.release() # deletes the underlying lok::Office handle ``` ``` -------------------------------- ### Advanced: choosing the Cython bridge explicitly Source: https://github.com/begonia-org/pylibreoffice Selects the Cython bridge by passing bridge='cython' to PyOffice. Any bridge value other than the literal 'pybind11' selects CyOffice. ```python from pylibreoffice.core import PyOffice # Any bridge value other than the literal "pybind11" selects CyOffice. office = PyOffice("/usr/lib/libreoffice/program", bridge="cython") ok = office.save_as("report.docx", "report.pdf") print(ok) ``` -------------------------------- ### Python usage via pybind11 bridge Source: https://github.com/begonia-org/pylibreoffice Usage through the pybind11 bridge, as the Python default backend does. It imports pylibreoffice.pybind11_office, creates an Office instance, calls save_as, and prints a message based on the result. ```python import pylibreoffice.pybind11_office as pybind_office office = pybind_office.Office("/usr/lib/libreoffice/program") ok = office.save_as("test.xls", "test_xls.pdf", "pdf") print("converted" if ok else "failed: document load or save returned false") office.release() ``` -------------------------------- ### release() -> bool Source: https://github.com/begonia-org/pylibreoffice Releases resources held by the Office instance. Always returns True. ```APIDOC ## release() -> bool ### Description Releases resources held by the Office instance. Always returns True. ### Method Function call ### Endpoint `Office.release()` ### Parameters #### Arguments - None ### Response #### Success Response - **bool** - Always `True` (the C++ `office::Office::release()` unconditionally returns `true` after deleting the `lok::Office` and nulling the pointer). ### Notes - Docstring: `"Release resources"`. ``` -------------------------------- ### Office.release Source: https://github.com/begonia-org/pylibreoffice Releases the LibreOffice instance and cleans up resources. This method should be called when the office instance is no longer needed. ```APIDOC ## Office.release ### Description Releases the LibreOffice instance and cleans up resources. This method should be called when the office instance is no longer needed. ### Method release ### Parameters None ### Response No return value documented. ### Request Example ```python import pylibreoffice.pybind11_office as pybind_office office = pybind_office.Office(bin_dir="/usr/lib/libreoffice/program/") ok = office.save_as(input_file="test.xls", output_file="test_xls.pdf", format="pdf") if not ok: print("conversion failed — no exception is raised; check the boolean") office.release() ``` ``` -------------------------------- ### CyOffice class definition (Cython) Source: https://github.com/begonia-org/pylibreoffice Full cdef class CyOffice wrapping office::Office. __cinit__ allocates the C++ object with new Office(libreoffice_dir) without null-check; __dealloc__ deletes it if non-NULL. save_as calls office.saveAs and returns bool; release calls office.release. ```cython cdef class CyOffice: cdef Office* office # 声明 C++ 指针 def __cinit__(self, str libreoffice_dir="/usr/lib/libreoffice/program"): self.office = new Office(libreoffice_dir) def __dealloc__(self): if self.office is not NULL: del self.office self.office = NULL def save_as(self, str input_file, str output_file, out_format="pdf")->bool: return self.office.saveAs(input_file, output_file, out_format) def release(self): self.office.release() ``` -------------------------------- ### release method implementation Source: https://github.com/begonia-org/pylibreoffice Deletes the lok::Office handle if non-null, sets the member pointer to null, and returns true. After release, the C++ office::Office object still exists but is unusable; saveAs will dereference the nulled pointer. ```cpp bool Office::release() { if (office){ delete office; } office = nullptr; return true; } ``` -------------------------------- ### Required format argument: missing format raises TypeError Source: https://github.com/begonia-org/pylibreoffice Shows that save_as requires the 'format' argument. Omitting it raises a TypeError with message 'save_as() missing required argument: \'format\'' on the pybind11 bridge. ```python import pylibreoffice.pybind11_office as pybind_office office = pybind_office.Office("/usr/lib/libreoffice/program") try: office.save_as("test.doc", "test.pdf") # format is MISSING except TypeError as exc: # pybind11: save_as() missing required argument: 'format' print("format argument is required on this bridge:", exc) ``` -------------------------------- ### Class declaration of office::Office Source: https://github.com/begonia-org/pylibreoffice Declares the office::Office class with a constructor, destructor, saveAs, and release methods. It wraps a lok::Office* handle. ```cpp class Office { public: Office(const std::string& bin_dir); ~Office(); bool saveAs(const std::string &input_file, const std::string& output_file, const std::string& format); bool release(); private: lok::Office *office = nullptr; }; ``` -------------------------------- ### C++ Office declaration (cdef extern) Source: https://github.com/begonia-org/pylibreoffice Cython extern declaration for the C++ class office::Office from src/office.hpp. Declares constructor taking string bin_dir, saveAs returning bint, and release returning bint. ```cython cdef extern from "office.hpp" namespace "office": cdef cppclass Office: Office(string bin_dir) bint saveAs(string input_file, string output_file, string out_format) bint release() ``` -------------------------------- ### Office destructor deletes lok::Office Source: https://github.com/begonia-org/pylibreoffice Destructor deletes the lok::Office handle if non-null and sets it to nullptr. Runs automatically on object destruction. ```cpp Office::~Office() { if (office) delete office; office = nullptr; } ```