Printing plain text

Plain text formats are great for working with on screens. They’re easy to generate and manipulate, and often presented with basic styling to highlight their structure.

For example, the output of the tree command shows a directory tree, with box drawing characters indicating the hierarchy, directory names in bold, and different colors for different file types.

Generating a printable equivalent of such things can be tricky. Let’s take a look at the options.

Problematic options

A lightweight solution

Fortunately, in 2015 the paps author released a new version on Github: paps 0.7.0. It now uses Cairo for its rendering and generates compact text-based files. It offers good basic styling options via a more complete implementation of Pango markup.

If you’re generating your own data, it’s easy to apply basic styling with Pango markup.

If you want to print some data that’s already already styled for the terminal, you can use Ansifilter to convert terminal control codes to Pango markup (or one of several other markup formats). You can remap the 16-color palette to your own set of RGB values.

This command converts the output of tree to a printable PDF with styling intact:

tree -C | ansifilter --pango | paps --markup --format=pdf > tree.pdf

For printing programming languages, there are several ways to apply syntax highlighting with terminal control codes, which you can then feed into Ansifilter. I like the pygmentize command from the Pygments project.

Heavyweights: HTML and CSS

To go beyond basic styling, you need to commit to a heavier-weight styling language, but you don’t have to write raw PostScript. You can use HTML and CSS.

First, generate some HTML yourself, or take HTML output from another tool. If your data can represented in a plain-text markup language like Markdown, reStructuredText or AsciiDoc, a tool like Pandoc can convert it to HTML, to which you can apply your own stylesheet.

CSS gives you a lot of control over presentation, including some features made specifically for print design, although you will need to check which features are implemented by your renderer.

You can manually print from a web browser, but there are also several tools for converting an HTML/CSS document to a PDF non-interactively. WeasyPrint focusses on CSS layout for paged media. PhantomJS and wkhtmltopdf can both produce PDFs using versions of the WebKit rendering engine.