How can I print from Vim to PDF?

I would have thought this is rather simple, but I don't get it done: I use gVim and would like to get the text as a PDF file. In other applications like Firefox the print dialog shows me available printers and I can choose to print directly to a PDF file. However, in Vim there is no such dialog and the file is just sent to the standard printer of the system.

I tried the following:

  • I'm not able to make the "print-to-pdf" thing my standard way of printing via the printer window of Ubuntu.
  • :ha > file converts my file to a .ps file. That's nice, but .pdf would be nicer...

Vim will not show you the print dialog box. Instead, you can print to a PostScript file, open it in a PostScript viewer and print from there.

To print to a PostScript file from Vim:

:hardcopy > myfile.ps

You can also convert PostScript to PDF using ps2pdf:

ps2pdf myfile.ps

Building on what others have already stated:

You can use the following single-line Vim command to create a PDF file:

:hardcopy > %.ps | !ps2pdf %.ps && rm %.ps

Note:

  • The % is shorthand for the current filename, so HelloWorld.C will print to HelloWorld.C.pdf
  • If you want to also retain the intermediate .ps file, simply omit the && rm %.ps, obtaining: :hardcopy > %.ps | !ps2pdf %.ps

Additionally, to change the rendered font, set the printfont before executing the hardcopy command. For example, to select Courier 8:

:set printfont=Courier:h8

Putting it all together, I decided to add the following to my .vimrc file so that I can simply execute the :HardcopyPdf command. This command can also operate on a selected range within a file:

" Select the font for the hardcopy
set printfont=Courier:h8
command! -range=% HardcopyPdf <line1>,<line2> hardcopy > %.ps | !ps2pdf %.ps && rm %.ps && echo 'Created: %.pdf'