py2pdf.py 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. #!/usr/bin/env python3
  2. from argparse import ArgumentParser
  3. from tempfile import mktemp
  4. from subprocess import call
  5. from sys import exit
  6. from os import remove
  7. from os.path import split, splitext
  8. def main(source_file, language, title, output, author):
  9. with open(source_file) as f:
  10. source = f.read()
  11. tmp = mktemp(suffix='.md')
  12. if output is None:
  13. output = splitext(split(source_file)[1])[0]+'.pdf'
  14. with open(tmp, 'w') as f:
  15. f.write(f'''---
  16. title: {title}
  17. author: {author}
  18. geometry: margin=2cm
  19. ---
  20. ```{language}
  21. {source}
  22. ```
  23. ''')
  24. retcode = call(['pandoc', '-o', output, tmp])
  25. remove(tmp)
  26. return retcode
  27. if __name__ == '__main__':
  28. parser = ArgumentParser()
  29. parser.add_argument('source_file')
  30. parser.add_argument('-l', '--language', default='python')
  31. parser.add_argument('-t', '--title', default='')
  32. parser.add_argument('-o', '--output', default=None)
  33. parser.add_argument('-a', '--author', default='')
  34. args = parser.parse_args()
  35. exit(main(args.source_file, args.language, args.title, args.output, args.author))