diff --git a/pptx_blueprint/__init__.py b/pptx_blueprint/__init__.py index 955988c..0ba6239 100644 --- a/pptx_blueprint/__init__.py +++ b/pptx_blueprint/__init__.py @@ -1,9 +1,14 @@ -import pathlib +from pathlib import Path import pptx from typing import Union, Iterable, Tuple from pptx.shapes.base import BaseShape +import subprocess +import tempfile +_Pathlike = Union[str, Path] -_Pathlike = Union[str, pathlib.Path] + +class LibreOfficeNotFoundError(FileNotFoundError): + pass class Template: @@ -85,8 +90,38 @@ def _find_shapes_in_slide(slide): def save(self, filename: _Pathlike) -> None: """Saves the updated pptx to the specified filepath. - Args: + Args: filename (path-like): file name or path """ # TODO: make sure that the user does not override the self._template_path pass + + def save_pdf(self, file_path: _Pathlike) -> None: + """Exports the updated pptx to the specified filepath as pdf file. + + Args: + file_path (path-like) file name or path + """ + + try: + subprocess.run(['libreoffice', '--version'], + stdout=subprocess.DEVNULL) # check if libreoffice is installed + + path = Path(file_path) + outdir = path.parent + file_name = path.name + + # create temporary directory + with tempfile.TemporaryDirectory() as tmpdirname: + template_temporary_path = f'{tmpdirname}/{file_name}' + + # save current Template as pptx in temporary directory + # TODO replace with self.save() method + self._presentation.save(template_temporary_path) + + export_cmd = ['libreoffice', '--headless', '--convert-to', + 'pdf', '--outdir', outdir, template_temporary_path] + p = subprocess.run( + export_cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + except FileNotFoundError: + raise LibreOfficeNotFoundError("Libre Office not found.") diff --git a/tests/test_template.py b/tests/test_template.py index a1ba1bd..76149f9 100644 --- a/tests/test_template.py +++ b/tests/test_template.py @@ -1,7 +1,9 @@ # TODO -from pptx_blueprint import Template +from pptx_blueprint import Template, LibreOfficeNotFoundError from pathlib import Path import pytest +import os +import subprocess @pytest.fixture @@ -38,3 +40,18 @@ def test_find_shapes_from_one_slide(template): def test_find_shapes_index_out_of_range(template): with pytest.raises(IndexError): shapes = template._find_shapes(0, 'logo') + + +def test_save_pdf(template): + try: + subprocess.run(['libreoffice', '--version'], + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) # check if libreoffice is installed + output_path = 'test/test.pdf' + template.save_pdf(output_path) + path = Path(output_path) + assert path.exists() == True + if path.exists(): + os.remove(path) + Path.rmdir(path.parent) + except FileNotFoundError: + pytest.skip()