The ImageFormatter
always creates a PNG output which width depends on the line length.
For example, this PNG is 192 pixels wide:
and this is 384:
Is there a setting in Pygments
to emulate a 80 column output, so all images will have the same width?
This is the code I used to produce the examples:
#!/usr/bin/python3
from pygments import highlight
from pygments import lexers
from pygments.formatters.img import ImageFormatter
from pygments.styles import get_style_by_name, get_all_styles
lexer = lexers.get_lexer_by_name('C')
source_short = 'printf("%d\\n", i);'
source_long = 'printf("variable i is equal to %d.\\n", i);'
formatter = ImageFormatter(full = True, style = get_style_by_name('vim'))
open('short.png', 'wb').write(highlight(source_short, lexer, formatter))
formatter = ImageFormatter(full = True, style = get_style_by_name('vim'))
open('long.png', 'wb').write(highlight(source_long, lexer, formatter))
I found that the easiest way to pad to 80 columns is to actually pad the first line of the file with extra blank spaces. This is my routine to read it:
def readCode(filename,columns):
with open(filename,'r') as f:
lines = f.read().split('\n')
maxw = max( [ len(line) for line in lines ] )
if maxw<columns:
lines[0] = lines[0] + ' '*(columns-maxw)
return '\n'.join(lines)
and then use it
code = readCode(filename, 80)
lexer = get_lexer_for_filename(filename)
highlight(code, lexer,
ImageFormatter(style=style),
outfile=outfilename)