10

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 to 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...
  • Not an answer, but you can use ps2pdf command-line tool afterwards, with the poscript file as input. – kebs Dec 4 '15 at 18:05
17

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

To print to a PS file from Vim:

:hardcopy > myfile.ps

You can also convert ps to pdf using ps2pdf:

ps2pdf myfile.ps
  • 1
    The first proposal means just changing the file extension... The second one might work in a mapping or something like that, I will have to do some more research to get that done... Thanks so far... – caligula Dec 4 '15 at 18:13
  • 1
    It is as easy as changing an extension ;) – Ron Dec 4 '15 at 18:15
  • 1
    This is awesome, definitely didn't know this was a thing! Can you get multiple files into a single document? – Ben Kushigian Mar 30 '17 at 17:20
  • 2
    (cygwin user) :ha > file.pdf did not create a valid pdf file. Combining it with ps2dpf did work but gives me white background. I'm happiest with :TOhtml file.html and then printing this html file to pdf – lucidbrot May 10 '17 at 6:35
  • I used a variation of this command today: :1,50 hardcopy, it didn't create a file, just printed from lines 1 to 50. – Dr Beco Mar 8 at 21:39
5

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 printerfont before executing the hardcopy command. For example, to select Courier 8:

:set printerfont=Courier:h8

Putting it all together, I opted to put the following in my .vimrc file so that I can simply execute the :HardcopyPdf command (which can also operate on a selected range within a file):

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

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.