How can I print well formatted code

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 😉

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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.

Method 2

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.

Method 3

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.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments