Open PDF files
From Vim Tips Wiki
Tip 1356 • Previous Tip • Next Tip
Created: October 8, 2006 Complexity: basic Author: Erez Volk+Sridharv Minimum version: 7.0 Karma: 41/26 Imported from: Tip#1356
Tools are available to extract text from a PDF document, and to create a PDF document from text. These tools can be used to allow Vim to open a pdf file, and even to write to the pdf file, although of course the resulting document will contain only unformatted text.
1. Get xpdf (for pdftotext) and cups-pdf. Xpdf package is available on all the major platforms. However cups-pdf is not available on Windows.
2. cups-pdf prints the pdf files and saves them in ~/PDF/ by default. It is assumed that these settings won't be changed.
3. Put the following commands in your vimrc:
autocmd BufReadPre *.pdf set ro nowrap autocmd BufReadPost *.pdf silent %!pdftotext "%" -nopgbrk -layout -q -eol unix - autocmd BufWritePost *.pdf silent !rm -rf ~/PDF/% autocmd BufWritePost *.pdf silent !lp -s -d pdffg "%" autocmd BufWritePost *.pdf silent !until [ -e ~/PDF/% ]; do sleep 1; done autocmd BufWritePost *.pdf silent !mv ~/PDF/% %:p:h
In a nutshell, the BufWritePost commands remove any file of similar name from ~/PDF, print the pdf to the directory, wait until the file is printed, then move the file to the current location. (Note: pdffg is the name of the pdf printer – check the name of the printer on your machine.)
If you open an existing pdf, it will be opened in readonly mode. You can write to it using :w! but that will remove existing formatting.
This tip allows you to use Vim to diff two pdf files.
[edit] See also
- View and diff MS Word files Uses a similar concept to open Word documents.
- Working with CSV files Uses a similar concept to open Excel spreadsheets.
[edit] Comments
On Unix with the fmt utility, a slight improvement is:
autocmd BufReadPost *.pdf silent %!pdftotext -nopgbrk "%" - |fmt -csw78
