Convert source code like hogehoge.py
to pdf file with syntax highlighting
Like the a2ps I used a long time ago
% cat hogehoge.txt | a2ps | lpr -Pprinter_name
For a while, I was looking for a tool that would allow me to print easily. But, I can't find a tool like this, so I had to make it myself.
I thought about using a pipe to feed the pdf file to the printer without creating it in vain, but I couldn't think of it. For the time being, I decided to output pdf.
I will paste the sauce. It's better if you're doing weird things or doing this! We would appreciate it if you could give us your opinions.
code2pdf
#!/usr/bin/env python
import sys
import os
import subprocess
if len(sys.argv) < 2:
print('Usage: %s FILENAME' % (sys.argv[0]))
sys.exit()
args = sys.argv
filename = sys.argv[1]
extension = filename.rsplit('.',1)
if extension[1] == 'py':
LANG = '{.python .numberLines}'
elif extension[1] == 'sh':
LANG = '{.sh .numberLines}'
elif extension[1] == 'html':
LANG = '{.html .numberLines}'
elif extension[1] == 'htm':
LANG = '{.html .numberLines}'
else:
LANG = ''
f = open(filename)
body = f.read()
f.close()
data_out = '# ' + filename + '\n' + '```'+ LANG +'\n' + body + '\n```'
subprocess.run(['pandoc',\
'-o',extension[0]+'.pdf',\
'--pdf-engine=lualatex',\
'-V', 'documentclass=bxjsarticle',\
'-V', 'classoption=pandoc,jafont=ipaex',\
'--highlight-style=kate',\
# '-H', '~/local/header.tex', #Write to preamble
'-V', 'linestretch:0.75',\
'-V', 'pagestyle:empty',\
'-V', 'geometry:top=8truemm',\
'-V', 'geometry:bottom=12truemm',\
'-V', 'geometry:left=20truemm',\
'-V', 'geometry:right=12truemm',\
'-V', 'papersize=a4',\
'-V', 'fontsize:9pt'],\
input=data_out, text=True, encoding='UTF-8')
$ code2pdf hogehoge.py
A screen capture of the above code in pdf.
You can change the color of syntax highlight.
Currently available settings can be found with the --list-highlight-styles
option.
The execution result in my environment is as follows.
$ pandoc --list-highlight-styles
pygments
tango
espresso
zenburn
kate
monochrome
breezedark
haddock
There is a color sample on this page.
Please also check.
Recommended Posts