Skip to content

Instantly share code, notes, and snippets.

@lem0n4de
Created December 19, 2018 15:09
Show Gist options
  • Select an option

  • Save lem0n4de/e08e0cce528fba385bfcc6a6e4eba2a0 to your computer and use it in GitHub Desktop.

Select an option

Save lem0n4de/e08e0cce528fba385bfcc6a6e4eba2a0 to your computer and use it in GitHub Desktop.
import os
import shutil
from pathlib import Path
from dataclasses import dataclass
import comtypes.client
@dataclass
class Item:
name: str
path: Path
output_path: Path
class Presentation(Item):
length: int = 0
def __str__(self):
return f'<name: {self.name} path: {self.path} length: {self.length}'
# main output directory
# home = Path(os.getenv("HOME"))
OUTPUT_DIR = Path('.') / 'ORCUN'
OUTPUT_DIR_ABS = OUTPUT_DIR.resolve()
# Function is from this answer: https://stackoverflow.com/a/31624001
def PPTtoPDF(ppt: Presentation,powerpoint ,formatType = 32):
input_path = str(ppt.path)
output_path = str(ppt.output_path)
print(input_path, output_path)
deck = powerpoint.Presentations.Open(f'{input_path}::hell::hell')
ppt.length = deck.Slides.Count
if deck.ReadOnly:
print(f"{input_path} is read-only.")
return
deck.SaveAs(output_path, formatType) # formatType = 32 for ppt to pdf
deck.Close()
def create_output_dir2(dir_name):
p = OUTPUT_DIR_ABS / dir_name
p.mkdir(exist_ok=True)
return p
def recursive_search_dir2(dir_name: Path, dir_dict: dict):
"""
Recursively searches directory and builds a dictionary of them.
"""
for item in dir_name.iterdir():
if item.is_dir():
if item.name == '__pycache__' or item.name == 'ORCUN':
continue
create_output_dir2(item)
# Build a recursive directory key in dictionary
dir_dict[item.name] = {}
recursive_search_dir2(item, dir_dict[item.name])
elif item.is_file():
if item.suffix == '.py' or item.suffix == '.json' or item.suffix == '.key':
continue
out_abs = OUTPUT_DIR_ABS / item.parent / item.name
if item.suffix == ".pptx" or item.suffix == ".ppt" or item.suffix == ".pps":
out_abs = out_abs.with_suffix('.pdf')
pre = Presentation(name=item.name, path=item.resolve(), output_path=out_abs.resolve())
dir_dict[item.name] = pre
else:
dir_dict[item.name] = Item(name=item.name, path=item.resolve(), output_path=out_abs.resolve())
def dict_items_to_pdf(dir_dict: dict):
powerpoint = comtypes.client.CreateObject("Powerpoint.Application")
powerpoint.Visible = 1
for key, value in dir_dict.items():
if isinstance(value, dict):
dict_items_to_pdf(value)
elif isinstance(value, Presentation):
if not value.output_path.exists():
PPTtoPDF(value, powerpoint)
elif isinstance(value, Item):
if not value.output_path.exists():
shutil.copy2(value.path, value.output_path)
powerpoint.Quit()
def main():
dir_dict = {}
recursive_search_dir2(Path("."), dir_dict)
dict_items_to_pdf(dir_dict)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment