Open pdf linux console

View pdf file in terminal

I want to view pdf files directly on our cluster rather than copying them to my local machine and then opening them in a viewer. How can I view a pdf file in my terminal?

If you’re connectiong to the cluster with ssh, I recommend using SSHFS. It provides a common solution to all “How do I do X with remote files” issues.

10 Answers 10

In many systems less uses lesspipe, which can handle pdftotext automatically. Therefore, you can immediately try

which will show the output of pdftotext in less .

For people like me who found this and get the error «no pdftottext available» just run apt-get install pdftohtml first to get this to work. Thanks to stackoverflow.com/questions/3570591/…

I guess, it is not possible to see PDF file in terminal but you can check it’s content by converting PDF file to text. You can do this as:

It will produce a.txt file which you can read into VIM.

For ubuntu-variant, this binary is available in following package.

It is possible to see a PDF file in the terminal, like so: pdftotext -layout file.pdf — | less (that’s how Ubuntu’s default lesspipe script does it)

I tried the following with good results:

pdftotext filname.pdf - | less 

When I want to «view a pdf file in terminal», that for me means that I want to actually see an uncompressed PDF, I do:

pdftk in.pdf output out.pdf uncompress 

I always wondered why both less in.pdf and less out.pdf give me just text strings in the PDF (and excluding the text-only PDF commands I’d expect in out.pdf ).

Well, that happens because of the lesspipe assuming I want pdftotext being run first — and since here I don’t, I have to specifically disable the lesspipe by setting LESSOPEN environment variable to nothing; that is:

And finally, I can view the uncompressed PDF code using less

Yet another solution. May I recommend to you the ancient utility mc .

MC(1) GNU Midnight Commander mc - Visual shell for Unix-like systems. 

mc is designed around text-based file-management, and it has a “view” option ( F3 key) which will automatically convert .pdfs to text for viewing without a GUI. The code which does this conversion is part of mc itself, so it does not require conversion by other utilities. (Also has a native .html viewer for WIW.)

mc’s viewer is very visually attractive compared to the other options here! To view a pdf without opening the file manager, you can use the -v option like this: mc -v file.pdf .

Need to work out how to suppress opening an X application for that extension though on double click. Using bottom menu is well functional.

This might be helpful, please note that:

  • It is for macOS only.
  • It won’t open the pdf inside the terminal window rather open a Quick look, which I find very powerful to see any file or documents quickly. Simply use:
Читайте также:  Тип ядра операционной системы linux

Maybe similar command in Linux called (gnome-sushi) I haven’t tested this, but might be helpful as well. I will update this post after testing it.

lesspipe is provided by the package less on Debian and Ubuntu.

One more solution is to use command gnome-open

Provided that you have login your server with -X option (ssh -X)

If you run emacs on your machine ( emacs comes preinstalled on Ubuntu 18.04), you can virtually open and see a pdf on a remote server by hitting Ctrl-x Ctrl-f (to find-file ) and then type in /user@hostname:/path/to/my.pdf and hit Enter (note the very first / ). You will then be prompted to enter the server’s password and there it is! You can see the pdf inside emacs.

Navigate through PDF inside emacs

Use space to go one page down and backspace to go one page up. You can also use arrow keys to scroll through a single page if it doesn’t fit in the screen.

Zoom in by hitting Ctrl-x Ctrl-+ . Zoom in more by hitting + only. Or zoom out more by hitting — .

Yes, you can connect to a remote server from within emacs using the build-in package tramp that works as simple as I explained above. This method works, not only for pdf, but for any other type of file, such as images.

Источник

How to View PDF File in Linux Command Line

Please note that this article seeks to explore viable ways of viewing (not opening) a PDF file from the Linux command-line environment. The creation of the PDF or Portable Document Format file type was inspired to solve/lessen the hurdles that made document sharing between operating systems and computers difficult.

Why View PDF File in Linux Command Line

Being able to view a PDF file from the Linux command-line environment is associated with the following benefits.

  • PDF maintains a document’s format. Once a document is created and saved in a PDF format, it cannot be altered like documents existing in .txt or .docx formats. Therefore, viewing such a document from the Linux command line environment should be the same as viewing it from a graphical PDF document reader.
  • PDF files are comparatively smaller than other document file formats making it easy for the Linux terminal environment to accommodate them.
  • Not all Linux users are tied to a Desktop environment where access to a graphical PDF reader application is easy. For users or Linux administrators bound to a Linux server operating system environment, this approach makes it easy to relatively preview PDF documents like receipts and invoices.

You might also like:

Problem Statement

We are going to need a sample PDF file which we will try to open and view from the Linux operating system command line.

Sample PDF File Viewing

The preview of the above file is from a graphical PDF reader application installed on a Linux operating system.

Let us break down the approaches to viewing PDF files from a Linux terminal.

Читайте также:  Show mysql users linux

Method 1: View PDF File Using less Command

The GNU General Public License makes it possible to use less utility from the Linux terminal to read input files. In comparison to graphical text editors like vi and nano, less command takes a shorter duration to read and display the targeted file on the Linux terminal window.

To view our PDF file (draft.pdf), we will run the following command.

View PDF in Linux Commandline

As expected, the PDF file format is retained.

Method 2: Combining pdftotext and less Commands

As stated on its naming convention, the pdftotext command utility is primarily effective in converting a PDF file to a text file.

Its usage syntax is as follows:

$ pdftotext [options] [PDF-file [text-file]]

However, we are not primarily interested in converting our sample PDF file to a text file format. We, therefore, need to temporarily convert the sample PDF file to a text file and then pipe the converted text file to the less command for viewing/display on the Linux terminal window.

Our modified syntax for this approach is as follows:

$ pdftotext [options] [PDF-file] - | less

The final implementation of the above command is as follows:

$ pdftotext draft.pdf - | less

View PDF in Linux Terminal

We have successfully learned how to read a PDF file as input and display/view it on a Linux command-line window.

Источник

Как легко открыть файл PDF из командной строки в Ubuntu

Что вы делаете, когда хотите открыть файл PDF в Ubuntu? Просто дважды щелкните значок файла PDF или щелкните правой кнопкой мыши и выберите параметр «Открыть с помощью средства просмотра документов». Но что, если вас попросят выполнить ту же задачу через командную строку? Знаете ли вы утилиту командной строки, которая сделает всю работу за вас?

Если вы не являетесь профессионалом в работе с командной строкой, я уверен, что ответ будет «НЕТ». К вашему сведению, Evince является средством просмотра документов по умолчанию для файлов PDF и PostScript в Ubuntu, а одноименная утилита выполняет эту работу за вас в случае, если вы хотите открыть файлы такого типа из командной строки.

Тем не менее, вы будете рады узнать, что есть способ, с помощью которого вы можете запустить Evince для файла PDF, даже если вы не знаете, что утилита командной строки с таким именем существует, и это то, что мы будем обсуждать в этой статье.

Обратите внимание, что все команды и инструкции, упомянутые в этой статье, были протестированы на Ubuntu 16.04LTS.

Альтернативный способ открытия файла PDF из командной строки

Излишне говорить, что всякий раз, когда мы обсуждаем способ выполнения определенной работы через командную строку, всегда задействована утилита командной строки. Это верно и в этом случае, так как существует утилита под названием gnome-open, которая поможет вам легко открывать PDF-файлы из командной строки. Вышеупомянутый инструмент можно загрузить и установить с помощью следующей команды:

sudo apt-get install libgnome2-bin

После успешной установки все, что вам нужно сделать, это выполнить следующую команду, чтобы открыть файл PDF:

Вот и все. Не нужно помнить, что существует инструмент под названием Evince, который обрабатывает PDF-файлы, так как gnome-open автоматически запустит Evince.

Круто, не так ли? Но теперь у некоторых из вас может возникнуть пара запросов, связанных с gnome-open. Нравится, как работает утилита, и поддерживает ли она только PDF-файлы. Что ж, позвольте мне ответить на них один за другим.

Читайте также:  Характеристика сетевой операционной системы linux

Что касается того, как работает gnome-open, он использует обработчики файлов GNOME для открытия файлов и URL-адресов, переданных ему в качестве аргументов. Этот процесс аналогичен тому, как файловый менеджер GNOME определяет приложение по умолчанию для открытия файла, когда вы дважды щелкаете значок файлов. gnome-open определяет MIME-тип файла, запускает приложение по умолчанию, связанное с этим MIME-типом, и передает имя файла (который пользователь хочет открыть) этому приложению.

Для сопоставления между типами mime и приложениями по умолчанию перейдите к файлу /etc/gnome/defaults.list на вашем компьютере с Ubuntu.

Теперь, переходя ко второму вопросу, объяснение, которое я предложил как часть ответа на первый вопрос, должно было дать вам представление о том, что gnome-open — это универсальная утилита, которая может открывать файлы любого типа. для тебя. И это тоже имеет смысл, так как в противном случае вам придется помнить gnome-open вместо Evince для PDF-файлов — та же проблема, с которой мы начали.

Таким образом, если файл в формате PDF, gnome-open откроет файл в средстве просмотра документов Evince, а если это текстовый файл, будет запущен Gedit.

Далее, вот несколько примеров использования gnome-open, которые могут оказаться полезными:

Чтобы открыть каталог в файловом менеджере Nautilus, выполните следующую команду:

Например, следующая команда откроет текущий рабочий каталог в Nautilus:

И следующая команда откроет каталог /tmp

Чтобы открыть веб-сайт в веб-браузере вашей системы по умолчанию, просто передайте URL-адрес в качестве аргумента gnome-open. Вот пример:

gnome-open https://linux-console.net/

Ниже приведены некоторые другие примеры, упомянутые на справочной странице утилит:

Open an OpenOffice.org document 
gnome-open Spinach.odf

Open a directory in Nautilus
gnome-open ~

Send an e-mail
gnome-open mailto:

Possible useless use of gnome-open
gnome-open /usr/share/applications/gedit.desktop

Ниже приведен список параметров командной строки, которые предлагает инструмент:

Help Options

-?, --help
Show a brief help message

--usage
Display a brief usage message

Bonobo activation Support

--oaf-ior-fd=FD
File descriptor to print IOR on

--oaf-activate-iid=IID
IID to activate

--oaf-private
Prevent registering of server with OAF

GNOME Library

--disable-sound
Disable sound server usage

--enable-sound
Enable sound server usage

--espeaker=HOSTNAME:PORT
Host:port on which the sound server to use is running

--version
Prints the version number

Обратите внимание, что версия gnome-open для KDE — это kde-open. Также существует универсальная версия, получившая название xdg-open, которая работает независимо от используемой среды рабочего стола.

Заключение

Короче говоря, если вы хотите открыть файл или URL-адрес с помощью приложения по умолчанию из командной строки, вам следует использовать gnome-open или другие подобные утилиты. Эти утилиты также можно использовать в случае, если вы забыли или не знаете, какую утилиту командной строки использовать для открытия определенного файла — случай, который мы обсуждали в этой статье.

Утилита gnome-open легко загружается и устанавливается, и ее использование также не представляет сложности. В большинстве случаев вам не потребуются какие-либо из его параметров командной строки, но, очевидно, это не всегда так, поэтому мы упомянули список здесь, в самом руководстве. В общем, полезный инструмент, который нужно иметь в своем арсенале.

Источник

Оцените статью
Adblock
detector