- pdftotext: Linux / UNIX Convert a PDF File To Text Format
- Install pdftotext under RedHat / RHEL / Fedora / CentOS Linux
- pdftotext syntax
- How do I convert a pdf to text?
- Further readings:
- Как преобразовать документ формата PDF в текстовый файл в терминале Linux
- How To Convert PDF To Text On Linux (GUI And Command Line)
- Convert PDF to text using Calibre (GUI)
- Convert PDF to text with pdftotext (command line)
- How to convert PDF to text in Linux.
- How to convert PDFs to text with the command line.
- Use an online PDF editor.
pdftotext: Linux / UNIX Convert a PDF File To Text Format
Question: I’ve downloaded configuration file in a PDF format. I do not have GUI installed on remote Linux / UNIX server. How do I convert a PDF (Portable Document Format) file to a text format using command line so that I can view file over remote ssh session?
Answer: Use pdftotext utility to convert Portable Document Format (PDF) files to plain text. It reads the PDF file, and writes a text file. If text file is not specified, pdftotext converts file.pdf to file.txt. If text-file is -, the text is sent to stdout.
Install pdftotext under RedHat / RHEL / Fedora / CentOS Linux
pdftotext is installed using poppler-utils package under various Linux distributions:
# yum install poppler-utils
OR use the following under Debian / Ubuntu Linux
$ sudo apt-get install poppler-utils
pdftotext syntax
- No ads and tracking
- In-depth guides for developers and sysadmins at Opensourceflare✨
- Join my Patreon to support independent content creators and start reading latest guides:
- How to set up Redis sentinel cluster on Ubuntu or Debian Linux
- How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
- How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
- A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
- How to protect Linux against rogue USB devices using USBGuard
Join Patreon ➔
How do I convert a pdf to text?
Convert a pdf file called hp-manual.pdf to hp-manual.txt, enter:
$ pdftotext hp-manual.pdf hp-manual.txt
Specifies the first page 5 and last page 10 (select 5 to 10 pages) to convert, enter:
$ pdftotext -f 5 -l 10 hp-manual.pdf hp-manual.txt
Convert a pdf file protected and encrypted by owner password:
$ pdftotext -opw ‘password’ hp-manual.pdf hp-manual.txt
Convert a pdf file protected and encrypted by user password:
$ pdftotext -upw ‘password’ hp-manual.pdf hp-manual.txt
Sets the end-of-line convention to use for text output. You can set it to unix, dos or mac. For UNIX / Linux oses, enter:
$ pdftotext -eol unix hp-manual.pdf hp-manual.txt
Further readings:
🐧 Get the latest tutorials on Linux, Open Source & DevOps via
Источник
Как преобразовать документ формата PDF в текстовый файл в терминале Linux
Оригинал: How to Convert a PDF File to Editable Text Using the Command Line in Linux
Автор: Lori Kaufman
Дата публикации: 9 ноября 2015 г.
Перевод: А.Панин
Дата перевода: 7 октября 2016 г.
Существует множество причин, по которым вам может понадобиться преобразовать документ формата PDF в текстовый файл. Возможно, вам нужно изменить старый документ и вас есть лишь его версия в формате PDF. Преобразование файлов PDF в ОС Windows не представляет каких-либо сложностей, но что делать в том случае, если вы используете Linux?
Не беспокойтесь, я продемонстрирую простую и рабочую методику преобразования файлов PDF в текстовые файлы с помощью утилиты с интерфейсом командной строки с именем pdftotext из пакета утилит «poppler-utils» . Эта утилита может быть уже установлена в вашей системе. Для проверки ее наличия в системе следует в первую очередь воспользоваться сочетанием клавиш «Ctrl+Alt+T» для открытия окна эмулятора терминала. Далее следует ввести следующую команду после приглашения командной оболочки и нажать клавишу «Enter» .
Примечание: если в статье написано, что нужно ввести какую-либо команду, причем сама команда помещена в кавычки, следует вводить ее без кавычек за исключением тех случаев, когда в статье четко указано обратное.
Если утилита pdftotext не установлена, следует ввести следующую команду после приглашения командной оболочки и нажать клавишу «Enter» :
После соответствующего запроса следует ввести свой пароль и нажать клавишу «Enter» :
В установленном пакете poppler-utils имеется множество других инструментов для преобразования документов формата PDF в различные форматы, осуществления манипуляций с файлами PDF и извлечения информации из этих файлов.
Следующая команда позволяет преобразовать файл PDF в текстовый файл. Воспользуйтесь сочетанием клавиш «Ctrl+Alt+T» для открытия окна эмулятора терминала, введите следующую команду после приглашения командной оболочки и нажмите клавишу «Enter» .
Вам придется заменить указанные пути к файлам на пути к оригинальному файлу формата PDF и результирующему текстовому файлу соответственно. Кроме того, вам придется изменить приведенные имена файлов на имена ваших файлов.
Созданный утилитой текстовый файл может быть открыт таким же образом, как и любой другой текстовый файл в Linux.
Результирующий текст будет содержать символы новых строк в тех местах, в которых их не должно быть. Это объясняется тем, что символы новых строк вставляются после каждой строки текста в файле PDF.
Вы можете сохранить оригинальное форматирование вашего документа PDF (заголовки, примечания, разделение на страницы и.т.д.) в результирующем файле с помощью флага «-layout» :
Если вы хотите осуществить преобразование диапазона страниц файла PDF, вам придется использовать флаги «-f» и «-l» (это «L» в нижнем регистре) для указания номеров первой и последней страниц из диапазона для преобразования:
Для преобразования файла PDF, зашифрованного с использованием пароля владельца, следует использовать флаг «-opw» (первым символом является буква «O» в нижнем регистре, а не цифра 0):
Замените строку «пароль» на пароль, с помощью которого был защищен оригинальный файл PDF. Убедитесь в том, что вы используете одинарные, а не двойные кавычки для выделения пароля.
Если же файл PDF зашифрован с использованием пароля пользователя, следует использовать флаг «-upw» вместо «-opw» . Остальная часть команды не должна изменяться.
Вы также можете указать набор символов новой строки, который будет использоваться в результирующем текстовом файле. Это особенно полезно в том случае, если вы планируете открывать этот файл в другой операционной системе, такой, как Windows или Mac OS, Для этой цели следует использовать флаг «-eol» (вторым символом является буква «O» в нижнем регистре, а не цифра 0), после которого должен следовать символ пробела и идентификатор выбранного набора символов новой строки ( «unix» , «dos» или «mac» ).
Примечание: если вы не укажите имя результирующего текстового файла, утилита pdftotext автоматически использует имя файла PDF, заменив его расширение на «.txt» . Например, имя файла «file.pdf» будет преобразовано в «file.txt» . Если вместо имени текстового файла использовать «-» , результирующий текст будет отправлен в стандартный поток вывода утилиты, что означает, что текст будет выводиться в окно эмулятора терминала и не будет сохраняться в текстовом файле.
Для закрытия окна эмулятора терминала следует нажать на кнопку «X» в его левом верхнем углу.
Для получения дополнительной информации об утилите pdftotext следует ввести команду «man page pdftotext» после приглашения командной оболочки в окне эмулятора терминала и нажать клавишу «Enter» .
Источник
How To Convert PDF To Text On Linux (GUI And Command Line)
This article presents 2 tools for converting PDF documents to editable text on Linux, using a graphical tool (Calibre) and a command line tool (pdftotext).
It worth noting that both tools used to extract text from PDF files mentioned in this article cannot extract the text if the PDF is made of images (for example scanned book pages / pictures).
Convert PDF to text using Calibre (GUI)
Calibre is a free and open source e-book software suite. It supports organizing, displaying, editing, and converting e-books, supporting a wide range of formats. The application runs on Linux, macOS, and Microsoft Windows.
Calibre should be available in your Linux distribution’s repositories, and you should be able to install it using whatever software store you have on your system. For example, to install it on Debian, Ubuntu, Linux Mint, Fedora, openSUSE, or Arch Linux, use:
- Debian, Ubuntu or Linux Mint:
- Fedora:
- openSUSE:
- Arch Linux:
Calibre may also be installed on Linux by using the Flathub package (requires setting up Flathub / Flatpak on some Linux distributions).
There’s yet another way to install Calibre on Linux explained on the application’s downloads page, where you’ll also find macOS and Windows binaries.
Now that Calibre is installed on your system, launch it and click Add books to add the PDF (or multiple PDFs — Calibre supports batch converting multiple PDF files to text) you want to convert to text.
From the list of books, select the PDF (or multiple PDFs for batch conversion to .txt) you want to convert to text, and click the Convert books button. In the upper right-hand side of the conversion window, choose TXT as the Output format :
There are many options you can tweak in this conversion dialog. For example, you can choose to automatically remove spacing between paragraphs, or insert a blank line between paragraphs ( Look & Feel -> Layout ). You can also set the character encoding and line ending style (system, unix, windows, old_mac), and even format it to markdown.
After you’re done with the configuration, click the OK button to start converting the PDF to text. The converted .txt file can be found in the directory where you’ve set the Calibre library location (and then in AuthorName/BookName subfolders; if the author or book name can’t be determined, the subfolder is called «Unknown»).
What Calibre lacks in this case is a way to only convert a page or a page range — it can currently only convert entire PDF files to text.
Convert PDF to text with pdftotext (command line)
pdftotext is a command line utility that converts PDF files to plain text. It has many options, including the ability to specify the page range to convert, maintain the original physical layout of the text as best as possible, set line endings (unix, dos or mac), and even work with password-protected PDF files.
pdftotextis part of the poppler / poppler-utils / poppler-tools package (depending on the Linux distribution you’re using). Install this package as follows:
- Debian, Ubuntu, Linux Mint, and other Debian/Ubuntu-based Linux distributions:
- Fedora:
- openSUSE:
- Arch Linux:
In other Linux distributions use your package manager to install the poppler / poppler-utils package.
Now that the package is installed, you can convert a PDF file to plain text and preserve its layout (I recommend using this -layout option for maintaining the original physical layout, but you can try it without it too) with:
You’ll need to replace input.pdf with the name of the PDF file, and output.txt with the name you want the generated TXT file to be called. Also add the paths before filenames if needed (e.g.
/Documents/mypdf.pdf ). If no output text file is specified, pdftotext will name the file with the same file name as the original PDF file.
The layout option preserves the PDF layout when converting it to text, even if multi-column PDF cases.
What if you want to only convert a page range of the PDF to text, instead of the whole PDF file? Use -f (first page to convert) and -l (last page to convert) followed by the page number, like this:
Replace M and N with the first and last page number to extract, and input.pdf with the PDF filename.
Want to use mac, dos or unix end-of-line characters? You can specify that too, using -eol followed by mac , dos or unix . E.g. for unix line endings:
If you don’t want to insert page breaks between pages, append -nopgbrk :
Want to batch convert all PDF files from a folder to text files? pdftotext doesn’t support batch PDF to text conversion (and pdftotext *.pdf doesn’t work), but you can convert all the PDF files in a folder to text files by using a Bash FOR loop:
For more options, run man pdftotext and pdftotext —help .
Источник
How to convert PDF to text in Linux.
Want to edit a PDF from your Linux device? Learn how to convert PDFs to text using commands or an online PDF editor.
How to convert PDFs to text with the command line.
Linux users can use a command line utility called pdftotext — which is part of the poppler tools package — to convert PDFs to plain text format.
To begin, install poppler tools package the command “sudo apt install poppler-utils.” This command works for Debian, Ubuntu, and Linux Mint distributions. Once the package is installed, run a second command to convert chosen files to plain text:
pdftotext -layout input.pdf output.txt
Replace the input.pdf with the file you want to convert and the output.txt with the name you want attached to the newly created text file. If you don’t choose a save location, your new file will automatically be saved in the same folder as the original PDF.
If you don’t need to edit and only want to copy or search text in a PDF, you can install an optical character recognition (OCR) tool instead. Linux OCR PDF tools read PDFs and add a searchable text file over the original PDF. That way, you can use functions like Ctrl+F and Ctrl+C to search and copy text in the PDF.
Use an online PDF editor.
If you’re not comfortable with command utilities, online PDF editors like Adobe Acrobat online services make it easy to convert PDFs into text formats like Microsoft Word.
You can easily convert a PDF to text on Linux without commands or downloads in three simple steps:
- Go to the Acrobat online PDF editor.
- Upload the PDF file you want to convert.
- Wait for the editor to transform your file.
- Download the newly created Microsoft Word DOCX file.
Once you download the DOCX file, you can open it using Microsoft Word and start editing right away.
Discover more about how Adobe Acrobat DC and Acrobat online services make it easy to convert PDFs to text online from your Linux device.
Источник