Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Parallelism and minor typing fix #4

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 30 additions & 1 deletion data.example.csv
Original file line number Diff line number Diff line change
@@ -1,4 +1,33 @@
name,id
NAME 1, 001
NAME 2, 002
NAME 3, 003
NAME 3, 003
NAME 4, 004
NAME 5, 005
NAME 6, 006
NAME 7, 007
NAME 8, 008
NAME 9, 009
NAME 10, 010
NAME 11, 011
NAME 12, 012
NAME 13, 013
NAME 14, 014
NAME 15, 015
NAME 16, 016
NAME 17, 017
NAME 18, 018
NAME 19, 019
NAME 20, 020
NAME 21, 021
NAME 22, 022
NAME 23, 023
NAME 24, 024
NAME 25, 025
NAME 26, 026
NAME 27, 027
NAME 28, 028
NAME 29, 029
NAME 30, 030
NAME 31, 031
NAME 32, 032
51 changes: 24 additions & 27 deletions main.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@
from pathlib import Path
import glob
import shutil
import concurrent.futures
from typing import Dict, List
import click
from pptx.enum.text import PP_ALIGN

from src.log import Log
from src.generatePPTX import generatePPTX
Expand Down Expand Up @@ -50,7 +50,7 @@ def main(
OUTPUT_FILE_PATH: Path to the output PDF file with the certificates. (default: ./output/certificates.pdf)
"""
options = {}
options['align'] = handleAlignOption(align)
options['align'] = align
options['font_size'] = font_size
options['color'] = color

Expand All @@ -73,38 +73,35 @@ def main(
os.makedirs(output_dir, exist_ok=True)
os.makedirs(Path(output_dir).joinpath('pptx'), exist_ok=True)

if multiple_fields:
parsed_data = readCSVConfig(data)
for value_row in parsed_data['values']:
print(f"Generating certificate for {value_row[0]}")
generateCertificate(model, parsed_data['fields'],
value_row, options, output_dir)
else:
parsed_data = readTXTConfig(data)
for name in parsed_data:
print(f"Generating certificate for {name}")
generateCertificate(model, ['name'], [name], options, output_dir)
try:
with concurrent.futures.ProcessPoolExecutor() as executor:
futures = []
if multiple_fields:
parsed_data = readCSVConfig(data)
for value_row in parsed_data['values']:
print(f"Generating certificate for {value_row[0]}")
futures.append(executor.submit(
generateCertificate, model, parsed_data['fields'],
value_row, options, output_dir))
else:
parsed_data = readTXTConfig(data)
for name in parsed_data:
print(f"Generating certificate for {name}")
futures.append(executor.submit(
generateCertificate, model, ['name'], [name], options, output_dir))
except Exception as e:
print(e)
print(type(e))

print("All certificates generated. Merging...")
file_paths = glob.glob(f"{output_dir}/*.pdf")
mergePDFs(file_paths, output_file_path)
print("Cleaning tmp files...")
shutil.rmtree("./tmp")
print("Done.")


def handleAlignOption(align: str):
if align == "left":
return PP_ALIGN.LEFT
elif align == "center":
return PP_ALIGN.CENTER
elif align == "right":
return PP_ALIGN.RIGHT
elif align == "justify":
return PP_ALIGN.JUSTIFY
else:
return None


def generateCertificate(model: str, fields: List[str], data: List[str], options: Dict[str, str], output_dir: str):
def generateCertificate(model: str, fields: List[str], data: List[str], options, output_dir: str):
pptx_path = generatePPTX(model, fields, data, options, output_dir)
PPTXtoPDF(pptx_path, output_dir)

Expand Down
17 changes: 13 additions & 4 deletions src/PPTXtoPDF.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,21 @@
from PyPDF2 import PdfFileReader, PdfFileWriter


def PPTXtoPDF(file_path: str, dir: str) -> None:
def PPTXtoPDF(file_path: Path, dir: str) -> None:

dir: Path = Path(dir).resolve()

# TODO Improve tmpfolder generation
tmpfolder = str(dir.parent) + "/tmp/" + "".join(str(file_path.stem).split()[0] + str(file_path.stem).split()[-1]) + "/0/"


subprocess.run(["libreoffice", "--headless", "--convert-to",
"pdf", "--outdir", dir, file_path], stdout=subprocess.DEVNULL)
"pdf", "--outdir", str(dir), file_path,
f"-env:UserInstallation=file://{tmpfolder}"], stdout=subprocess.DEVNULL)


generated_file_path = Path(dir).joinpath(
Path(file_path).stem + ".pdf")
generated_file_path = dir.joinpath(
file_path.stem + ".pdf")

reader = PdfFileReader(generated_file_path)
writer = PdfFileWriter()
Expand Down
17 changes: 15 additions & 2 deletions src/generatePPTX.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,22 @@
from pptx import Presentation
from pptx.util import Pt
from pptx.dml.color import RGBColor
from pptx.enum.text import PP_ALIGN

def handleAlignOption(align: str):
if align == "left":
return PP_ALIGN.LEFT
elif align == "center":
return PP_ALIGN.CENTER
elif align == "right":
return PP_ALIGN.RIGHT
elif align == "justify":
return PP_ALIGN.JUSTIFY
else:
return None

def generatePPTX(model: str, fields: List[str], data: List[str], options: Dict[str, str], output_dir: str) -> str:
def generatePPTX(model: str, fields: List[str], data: List[str], options, output_dir: str) -> Path:
align = handleAlignOption(options['align'])
prs = Presentation(model)
slide = prs.slides[0]

Expand All @@ -21,7 +34,7 @@ def generatePPTX(model: str, fields: List[str], data: List[str], options: Dict[s
frame.text = frame.text.replace(field_placeholder, data[field_index])

for paragraph in frame.paragraphs:
paragraph.alignment = options['align']
paragraph.alignment = align
paragraph.font.size = Pt(options['font_size'])
paragraph.font.color.rgb = RGBColor.from_string(
options['color'])
Expand Down