refactor for readability
This commit is contained in:
45
app/pdf.py
45
app/pdf.py
@@ -2,6 +2,8 @@ import os
|
||||
import subprocess
|
||||
import tempfile
|
||||
|
||||
POSTSCRIPT_FILEPATH = "tempfile.ps"
|
||||
|
||||
|
||||
def make_pdf(
|
||||
problems: str, answers: str, output_path: str, include_answers: bool
|
||||
@@ -11,29 +13,32 @@ def make_pdf(
|
||||
else:
|
||||
pdf_jobs = ("problems", problems)
|
||||
|
||||
for job_name, job in pdf_jobs:
|
||||
|
||||
for job_name, text in pdf_jobs:
|
||||
if job_name == "answers":
|
||||
path, filename = os.path.split(output_path)
|
||||
new_filename = f"{filename.split('.pdf')[0]}-answers.pdf"
|
||||
output_path = os.path.join(path, new_filename)
|
||||
|
||||
output_path = make_answers_path(output_path)
|
||||
with tempfile.NamedTemporaryFile(mode="w") as txt_file:
|
||||
txt_file.write(job)
|
||||
txt_file.flush()
|
||||
write_to_txtfile(txt_file, text)
|
||||
make_postscript_file(txt_file)
|
||||
make_pdf_file(output_path)
|
||||
os.unlink(POSTSCRIPT_FILEPATH)
|
||||
|
||||
command = (
|
||||
f"enscript --columns=4 --no-header --output=tempfile.ps {txt_file.name}"
|
||||
)
|
||||
print(f"command: '{command}'")
|
||||
|
||||
output = subprocess.check_output(command, shell=True)
|
||||
print(output)
|
||||
def make_answers_path(path):
|
||||
path, filename = os.path.split(path)
|
||||
new_filename = f"{filename.split('.pdf')[0]}-answers.pdf"
|
||||
return os.path.join(path, new_filename)
|
||||
|
||||
command = f"ps2pdf tempfile.ps {output_path}"
|
||||
print(f"command: '{command}'")
|
||||
|
||||
output = subprocess.check_output(command, shell=True)
|
||||
print(output)
|
||||
print("made pdf", output_path)
|
||||
os.unlink("tempfile.ps")
|
||||
def write_to_txtfile(txt_file, text):
|
||||
txt_file.write(text)
|
||||
txt_file.flush()
|
||||
|
||||
|
||||
def make_pdf_file(output_path):
|
||||
command = f"ps2pdf {POSTSCRIPT_FILEPATH} {output_path}"
|
||||
subprocess.call(command, shell=True)
|
||||
|
||||
|
||||
def make_postscript_file(txt_file):
|
||||
command = f"enscript --columns=4 --no-header --output={POSTSCRIPT_FILEPATH} {txt_file.name}"
|
||||
subprocess.call(command, shell=True)
|
||||
|
||||
Reference in New Issue
Block a user