Convert ppt-to-image (automate ppt to image) on Mac with python
step 1 :
pip install python-pptx pythonnet
step 2 :
install homebrew on Mac
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
领英推荐
step 3 :
brew install --cask libreoffice
brew install poppler
step 4 :
Run below code for actual magic!
import os
from pptx import Presentation
from pathlib import Path
def convert_ppt_to_images(input_path, pptx_file, output_dir):
if not os.path.exists(output_dir):
os.makedirs(output_dir)
pptx_file = os.path.join(input_path, pptx_file)
# Validate pptx_file path
if not os.path.isfile(pptx_file):
print(f"Error: PPTX file '{pptx_file}' not found.")
return
# Specify the file name
pdf_file = os.path.join(output_dir, Path(pptx_file).stem + ".pdf")
# Creating a file at specified location
with open(os.path.join(input_path, pdf_file), 'w') as fp:
pass
convert_command = f"soffice --headless --convert-to pdf \"{pptx_file}\" --outdir \"{output_dir}\""
os.system(convert_command)
# Check if PDF conversion was successful
if not os.path.isfile(pdf_file):
print(f"Error: PDF file '{pdf_file}' could not be created.")
return
# Convert each page of the PDF to an image
pdftoppm_command = f"pdftoppm -png \"{pdf_file}\" \"{output_dir}/slide\""
os.system(pdftoppm_command)
# Rename output files to slide_1.png, slide_2.png, etc.
for i, file_name in enumerate(sorted(os.listdir(output_dir))):
if file_name.startswith('slide-') and file_name.endswith('.png'):
os.rename(
os.path.join(output_dir, file_name),
os.path.join(output_dir, f"slide_{i + 1}.png")
)
print(f"Slides from {pptx_file} have been converted to images in {output_dir}")
# Example usage
input_path = # Replace with PowerPoint directory path
pptx_file = # Replace with your PowerPoint file path
output_dir = os.path.join(input_path, Path(pptx_file).stem.replace(" ","_"))
# Function for conversion ppt to images
convert_ppt_to_images(input_path, pptx_file, output_dir)