24

Similar to using markdown on Stack Overflow to create monospace output, how can I do that for my programs.

I tried lp filename.txt and was pleasantly please to find that it was able to use the local network printer and print 'as is'

The problem is the output is not mono-spaced.

Is there an quicker option than...

1) copy the text
2) paste into a text doc
3) format the document as mono
4) print it 

I would love to find some option like lp filename.txt -format=mono ;)

Randall
  • 445

3 Answers3

26

You can use the vim editor to pretty print arbitrary files vim can read. Use the following to create a PostScript file.

vim \
  -c 'hardcopy > output.ps' \
  -c quit <input_file>

If you want a PDF file, add && ps2pdf output.ps to the command line.

You can also write a small script that pastes the current clipboard content into a temporary file, runs vim on the file, prints the resulting file and deletes the temporary file.

Marco
  • 33,548
  • 1
    A good option for your vimrc for when you print code is set printoptions=portrait:n to print in landscape mode. – oligofren Apr 08 '15 at 12:03
  • 1
    I'm probably not the only one here that wanted to turn off page headers once printing worked. You can turn them off by adding set printoptions=header:0 to vimrc. – Andy Gaskell Sep 14 '15 at 18:11
  • For HTMl you can do vim -c TOhtml -c write -c quit <input_file> – Matthew Cline Nov 23 '15 at 21:40
  • 1
    Oops, that should be vim -c 'set cmdheight=2' -c TOhtml -c write -c quit -c quit <input_file> – Matthew Cline Nov 23 '15 at 21:51
  • @AndyGaskell I've asked a question, please see if you can solve it: http://unix.stackexchange.com/questions/315363/vim-prntoptions-wont-accept-two-options-simultanenously – an offer can't refuse Oct 10 '16 at 02:23
  • Vim's default printerfont is too large for many peoples taste. You can edit it using the following syntax: :set printerfont=Courier:h8 – arr_sea Sep 27 '19 at 18:43
13

The shortest path here is probably to use a2ps, it generates monospaced postscript by default.

You can install a2ps with brew, i.e. brew install a2ps

Depending on its setup, it will send the output directly to stdout or lp, override with -o. Also, a2ps recognizes several programming languages and pretty-prints them.

a2ps -o output.ps infile.text

Use --pro=color if color is available:

a2ps --pro=color -o output.ps infile.text

For HTML output I tend to use vim's 2html feature.

Thor
  • 17,182
5

a2ps was the answer. I installed it with brew:

brew install a2ps

Now I can a2ps myfilename and it works.

Unfortunately it comes out landscape and if I try to make it portrait it's squished over to the left and tiny, only up taking 50% of the page. [upate - found fix to this with parameter -1 (for number of pages to find on one sheet - the default was 2)

However as landscaped it worked and the code has the fixed format style I was looking for.