Skip to content

Instantly share code, notes, and snippets.

@no1xsyzy
Created February 5, 2018 15:29
Show Gist options
  • Save no1xsyzy/8cb018e2f808077271e9b2c37ee61559 to your computer and use it in GitHub Desktop.
Save no1xsyzy/8cb018e2f808077271e9b2c37ee61559 to your computer and use it in GitHub Desktop.
A ppt2pdf converter. Only work on Windows with PowerPoint software installed. Licensed with Apache License, Version 2.0 (https://www.apache.org/licenses/LICENSE-2.0).
# Copyright [2018] [Siyuan "no1xsyzy" Xu]
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import comtypes.client
import traceback
from pathlib import PurePath, Path
what=0
def PPTtoPDF(inputFileName, outputFilePattern="{basename}.pdf", formatType = 32):
# Partially from <https://stackoverflow.com/a/31624001/6202760>
powerpoint = comtypes.client.CreateObject("Powerpoint.Application")
powerpoint.Visible = 1
suffix = PurePath(inputFileName).suffix
outputFileName=outputFilePattern.format(
inputFileName,
name=inputFileName,
suffix=suffix,
ext=suffix.lstrip("."),
basename=inputFileName[:-len(suffix)])
print("converting '{}' to '{}'".format(inputFileName, outputFileName))
deck = powerpoint.Presentations.Open(inputFileName)
deck.SaveAs(outputFileName, formatType) # formatType = 32 for ppt to pdf
deck.Close()
powerpoint.Quit()
if __name__ == "__main__":
import sys
outfp = "{basename}.pdf"
infns = []
itargv = iter(sys.argv[1:])
for arg in itargv:
if arg == "-o" or arg == "--output": # support output pattern tweak
if arg == "-o" and len(arg)>2:
outfp = arg[2:]
elif arg == "--output=" and len(arg)>9:
outfp = arg[9:]
else:
outfp = next(itargv)
elif "*" in arg: # support glob
infns.extend(str(i.resolve()) for i in Path().glob(arg))
elif Path(arg).is_dir(): # support directory
infns.extend(str(i.resolve()) for i in Path(arg).rglob("*.ppt"))
infns.extend(str(i.resolve()) for i in Path(arg).rglob("*.pptx"))
else:
infns.append(arg)
for infn in infns:
if what:
print("converting '{}' to pattern '{}'".format(infn, outfp))
continue
try:
PPTtoPDF(infn, outfp)
except Exception as e: # sometimes will fail to no reasom (manually publish also failed)
traceback.print_exc()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment