18

I use the following command to print a directory structure to a file:

tree -h somepath/ > tree_of_somepath.txt

tree gives a nice colorized output on the terminal, but as expected this cannot be redirected to a text file. I would like to print the output of tree to a pdf file and preserve the color.

Any ideas?

1
  • If you don't need the color (as the OP does), you can still get usable tree output using tree -n -d --charset unicode > file. It's definitely not as pretty, but I use it with a monochrome laser printer when I'm herding my data files, etc..
    – Joe
    Jul 15, 2015 at 21:18

1 Answer 1

24
  1. Install the following dependencies:

    sudo apt-get install aha wkhtmltopdf
    
  2. Save your tree command output to html with aha:

    tree -C -h | aha > foo.html
    

    From the tree man page, -C forces colorization:

        -C     Turn colorization on always, using built-in color defaults
               if the LS_COLORS environment variable is not set. Useful to
               colorize output to a pipe.
    
  3. Finally export the html to pdf with wkhtmltopdf:

    wkhtmltopdf foo.html foo.pdf
    

Example:

cd /tmp
tree -C -h | aha > foo.html
wkhtmltopdf foo.html foo.pdf
xdg-open foo.pdf

enter image description here

3
  • Perfect, though I omitted the --black to save some toner, when it lands on paper ;)
    – Bruni
    Jul 13, 2015 at 9:54
  • @Bruni Good idea :) Let me edit the answer Jul 13, 2015 at 9:55
  • $ wkhtmltopdf foo.html foo.pdf wkhtmltopdf: cannot connect to X server
    – uss
    Oct 27, 2017 at 12:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.