Spaces:
Sleeping
Sleeping
File size: 1,786 Bytes
dbb3f80 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 | import os
import shutil
import sys
# For .docx conversion
try:
from docx2pdf import convert as docx_convert
except ImportError:
print("Error: docx2pdf not installed. Run 'pip install docx2pdf' and try again.")
sys.exit(1)
# For .pptx conversion (requires PowerPoint installed)
try:
import win32com.client
except ImportError:
print("Error: pywin32 not installed. Run 'pip install pywin32' and try again.")
sys.exit(1)
def main(input_dir, output_dir):
if not os.path.isdir(input_dir):
print(f"Error: {input_dir} is not a directory.")
sys.exit(1)
os.makedirs(output_dir, exist_ok=True)
for root, dirs, files in os.walk(input_dir):
rel_dir = os.path.relpath(root, input_dir)
target_subdir = os.path.join(output_dir, rel_dir)
os.makedirs(target_subdir, exist_ok=True)
for file in files:
filepath = os.path.join(root, file)
base, ext = os.path.splitext(file)
output_pdf = os.path.join(target_subdir, base + '.pdf')
if ext.lower() == '.docx':
docx_convert(filepath, output_pdf)
elif ext.lower() == '.pptx':
try:
ppt_app = win32com.client.Dispatch("PowerPoint.Application")
pres = ppt_app.Presentations.Open(os.path.abspath(filepath), WithWindow=False)
pres.SaveAs(output_pdf, 32) # 32 = ppSaveAsPDF
pres.Close()
ppt_app.Quit()
except Exception as e:
print(f"Failed to convert {filepath}: {e}. PowerPoint installed?")
elif ext.lower() == '.pdf':
shutil.copy(filepath, output_pdf)
main("OrigFolder","ConvertedFiles") |