Printing Text Files To PDF With Enscript
Sometimes you want to print a text file and apply some fancy formatting -- say, a header with page numbering, or printing two-pages per sheet to conserve paper. You have several options under Linux:
- Open the file in a word processor and apply the formatting before printing.
- Change the printer drivers applied to the file when it prints. This requires tinkering with .PPD or filter files on the CUPS printer server.
- Print the file using a utility command like a2ps or enscript.
I prefer the last approach, because it gives me the most flexibility. I can customize the output by varying the parameters. Plus, many text editors let you specify the command line to use for printing.
Neither of these utilities has all the features I'd like, but they get the job done. I chose
a2ps because enscript is able to word-wrap long lines.
enscript packagein Debian/Ubuntu:
sudo apt-get install enscript
Then run it in the format
enscript <parameters> <filename>
enscript -B -i 2 -f Courier8 --margins=26:18:18:18 MyTextFile.txt
Prints the file MyTextFile.txt with no page header, indenting each line 2 characters, using the font Courier8, with left_right:top margins of 26:18:18:18 in points.
enscript -2 -r -j --font=Times-Roman11 --word-wrap --mark-wrapped=arrow MyTextFile.txt
Prints 2-up, landscape orientation, with borders, using TimesRoman11 font, wrapping words that extend beyond the right margin using the arrow symbol. A typical page looks like this:
Sample page produced by Enscript, using 2-up printing
I set my Default Printer in Ubuntu 9.04 to the PDF printer. Enscript will then send all output to a PDF file, and I can verify its appearance before deciding to print hardcopy. Here's a way to extend the last example generically and automatically load the PDF for preview. I use this command in the Geany text editor (
Edit | Preferences | Printing | Use an external command for printing).
enscript -2 -r -j --font=Times-Roman11 --word-wrap --mark-wrapped=arrow '%f' && sleep 2 && evince ~/PDF/_stdin_.pdf
'%f' designates the filename parameter. To make it work in the Geany editor, I've found that it must be typed in single quotes. The
&& sleep 2 && evince ~/PDF/_stdin_.pdf commands will wait 2 seconds for the print job to finish, then run the Evince PDF viewer to display the file
_stdin_.pdf you just generated in the user's PDF subdirectory.
This post was originally published on my other blog, https://tech.surveypoint.com