Linux word to text

We’re searching a programm that allows us to convert a doc or docx document to a txt file. We’re working with linux and we want to start a website that converts user uploaded doc files. We don’t wanna use open office/libre office cause we have bad experience with that. Pandoc can’t handle doc files :/

Anyone have a idea?

Kara's user avatar

Kara

6,08516 gold badges51 silver badges57 bronze badges

asked Jun 28, 2011 at 16:59

user698601's user avatar

You will have to use two different command-line tools, depending if you are working with .doc or .docx format.

For .doc use catdoc:

catdoc foo.doc > foo.txt

For .docx use docx2txt:

docx2txt foo.docx

The latter will produce a file called foo.txt in the same directory as the original.

I’m not sure which Linux distribution you are using, but both catdoc and docx2txt are available from the Ubuntu repositories, for example:

apt-get install docx2txt

Or with Homebrew on Mac:

brew install docx2txt

David Wolever's user avatar

David Wolever

146k86 gold badges337 silver badges496 bronze badges

answered Nov 12, 2016 at 15:10

harlandski's user avatar

harlandskiharlandski

3562 silver badges4 bronze badges

2

here is a perl project which claims to do it. I have done a lot of this by hand also, using XSLT on the document.xml. the Docx file itself is just a zip file, you can unzip it and inspect the elements. I will say that this is not hard to do for specific files, but is very hard to do in the general case, because of the lack of documentation for how Word internally stores things, and the variance of internal representation.

answered Jun 28, 2011 at 17:03

Paul Sanwald's user avatar

Paul SanwaldPaul Sanwald

10.8k6 gold badges43 silver badges59 bronze badges

For doc files you may use antiword, it’s available on Homebrew and Ubuntu.

answered Mar 3, 2020 at 8:35

Mishari's user avatar

MishariMishari

3063 silver badges14 bronze badges

You can also use pandoc:

Keep the layout (newline as in the visualization of the document):

pandoc -s mydocument.docx  -o ouput.txt

Newline only when the original text has a newline command:

pandoc --wrap=none -s mydocument.docx  -o ouput.txt

answered Jan 26, 2022 at 10:10

G M's user avatar

G MG M

20.2k10 gold badges83 silver badges83 bronze badges

Abiword can convert from the commandline between any file formats it knows.

Convert from Word to plain text:

abiword --to=txt myfile.doc

Make a pdf from a Word file:

abiword --to=pdf myfile.doc

And so on. The results in these cases would be myfile.txt or myfile.pdf. If you want to specify the output name you can do that too:

abiword --to=txt --to-name=output.txt myfile.doc

Convert ODT to Word:

abiword --to=doc myfile.odt

Convert Word to ODT:

abiword --to=odt myfile.doc

In fairness to other answers, it should be noted that AbiWord uses wvWare to handle Word documents, but even the wvWare homepage recommends using AbiWord instead for most conversions.

I hate word processors. This is the main reason I have AbiWord installed.

You might also be interested in unoconv, which is a similar tool supporting formats OpenOffice knows (which would include spreadsheets and the like), but I have no experience with it personally.

Содержание

  1. Как легко конвертировать форматы документов в Linux
  2. Базовая установка и использование Pandoc
  3. Параметры командной строки Pandoc
  4. Справочные файлы ODT / DOCX
  5. Бэкэнд рендеринга PDF
  6. Генератор электронных книг
  7. Дополнительные советы
  8. Уценка Пандока
  9. Используйте графический интерфейс с Pandoc
  10. Пандок снимает стресс от переключения
  11. Word to text linux
  12. About
  13. Converting .docx files to plain text and preserving line breaks to maintain line number references to source document: howto & implications?
  14. 1 Answer 1

Как легко конвертировать форматы документов в Linux

Одной из часто упоминаемых проблем с переходом на Linux является совместимость файлов. Вы неизменно будете отправлять пользователям файлы других операционных систем, и они не будут выглядеть одинаково при открытии в таких приложениях, как Word. Пока вы можете установить шрифты или попробовать виртуальные машины или эмуляторы

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

Одним из инструментов, который вы можете использовать для преобразования между форматами, является pandoc, необходимый инструмент в наборе инструментов любого пользователя Linux.

Базовая установка и использование Pandoc

Установка pandoc в большинстве дистрибутивов Linux — это простая поездка в репозитории. В системах на основе Ubuntu следующая команда установит его для вас:

После установки вы можете начать использовать программу командной строки для преобразования файлов. Отлично справляется с Markdown и другими легкими языками разметки, если у вас есть .Мэриленд файл лежит вокруг, вы можете преобразовать это в HTML с помощью следующего:

флаг говорит имя выходной файл ты хочешь. В этом случае он также выводит формат вывода (HTML) по расширению имени файла. Вы можете использовать (за читать) а также -вес (за записывать) флаги, чтобы сообщить pandoc тип конверсии, который вы хотите. Предположим, вы привыкли писать в Markdown, но вам нужно что-то опубликовать на странице на MediaWiki:

В своих более ранних версиях pandoc фокусировался на «обновлении» файлов в том смысле, что он мог преобразовывать более простые форматы (такие как Markdown) в более сложные (например, ODT или Microsoft DOCX). Но это будет сейчас читать эти более сложные форматы, а также. Это означает, что если вы привыкли к текстовому процессору, но соблазнены всеми причинами использовать меньший и более портативный текстовый формат

стало намного проще.

Учитывая каталог, полный файлов Word, следующая команда преобразует каждый из них в Markdown:

Обратите внимание, что это оставит вас с именами файлов filename.docx.md, так что вам нужно будет выполнить команду быстрого переименования (или, что еще лучше, добавить ее к вышеупомянутому сценарию оболочки)

Параметры командной строки Pandoc

Теперь, когда у вас есть некоторые основы, мы рассмотрим некоторые из более сложных опций параметров командной строки pandoc.

Справочные файлы ODT / DOCX

Предположим, вы преобразовали все свои старые, громоздкие файлы текстового процессора в Markdown. Пока вы наслаждаетесь радостью от написания простого текста, в какой-то момент вам придется поделиться этим с кем-то. И этот кто-то может быть не так просвещен, как вы. Вы можете просто полностью изменить читать а также записывать флаги для преобразования вашего файла обратно в формат Word:

Но некоторым людям нравятся их файлы Word с определенными шрифтами, пронумерованными заголовками и т. Д. DOCX back-end поддерживает файлы шаблонов, называемые справочные файлы, как раз для такого случая. Это ODT или же DOCX файлы, которые вы настроили со всем необходимым стилем. Затем pandoc применяет эти стили при преобразовании, если вы передаете ему ссылочный файл в командной строке:

Обратите внимание, как шрифты, настроенные в справочном файле выше (Arial Black для заголовка 1 и т. Д.) Отображаются в преобразованном файле ниже. Вы можете создать столько эталонных файлов, сколько вам нужно (например, по одному на клиента). Затем полностью игнорируйте форматирование во время написания и применяйте стили за один шаг при конвертации.

Бэкэнд рендеринга PDF

Создание PDF-файлов также является простым упражнением после установки необходимых пакетов. Облегченный способ получить возможность записи в формате PDF — это установить wkhtmltopdf пакет, инструмент командной строки для преобразования HTML в PDF. Pandoc поддерживает это изначально, так что если вы установите записывать флаг HTML, но выходной файл как PDF, он будет интерпретировать это как ваше намерение использовать wkhtmltopdf все само собой!

Кроме того, вы можете перейти к полнофункциональной опции с помощью системы набора текста TeTex. Воспользуйтесь тем, что эти пакеты Предлагаемые установки для пакета pandoc, переустановив с помощью следующей команды:

Затем откиньтесь на спинку кресла, пока много (на самом деле, много) пакетов устанавливаются. Как только они будут завершены, вы можете преобразовать свой файл непосредственно в PDF, указав его как записывать флаг:

В то время как wkhtmltopdf Опция требует установки только одного пакета, вы можете получить более удобные для печати результаты с TeTex. А именно, шрифты с засечками используются по умолчанию, а страницы автоматически нумеруются.

Генератор электронных книг

Наконец, pandoc может конвертировать ваши файлы в электронные книги, подходящие для чтения на телефоне или в электронном ридере.

, EPUB а также EPUB3 Бэк-энд даст вам правильно отформатированную книгу:

Дополнительные советы

Преимущества pandoc выходят за рамки его возможностей в качестве утилиты командной строки … например, она включает поддержку улучшенной версии Markdown и может быть легко интегрирована с графическими приложениями.

Уценка Пандока

В дополнение к тому, что pandoc является инструментом конвертации, он поддерживает слегка улучшенную версию Markdown. Используя pandoc вместо стандартного уценка Команда, у вас есть некоторые дополнительные функции, в том числе следующие:

  • Метаданные — Разновидность Pandoc в Markdown позволяет вам включать в заголовок вашего документа такую ​​информацию, как автор, дата, адрес электронной почты и т. Д.
  • Текстовые украшения — Вы можете применять текстовые декорации, такие как зачеркивание или супер / подстрочный, которые не поддерживаются в стандартной Markdown через pandoc.
  • таблицы — Это само по себе делает Пандок стоящим по сравнению с «ванильной» уценкой. Используя символ конвейера для разделения ячеек таблицы, вы можете создать таблицу, которая варьируется от действительно уродливой до удобочитаемой как в обычном тексте, так и в визуализированном формате.
  • Необычные списки — Pandoc позволяет форматировать списки с уровнями в стиле структуры, например, «1.», затем «A.», затем «i.» И т. Д. Вы также можете указать начальный номер для списков, где списки в простой уценке начинаются с «1.»
  • Подсветка синтаксиса кода — Вы можете применить подсветку к своим блокам кода, сообщив Pandoc, что это за язык.

Выше приведены только некоторые функции Pandoc Markdown. Посетите страницу руководства на pandoc.org для получения полного списка дополнительных возможностей, предоставляемых этим вариантом Markdown.

Используйте графический интерфейс с Pandoc

Хотя pandoc эффективен как инструмент командной строки, он содержит много опций. Если вы новичок в Linux, вы можете предпочесть использовать pandoc с графическим интерфейсом. Хотя по умолчанию он не содержит графического интерфейса, вы можете установить PanDocElectrion конвертировать ваши документы с указателем и щелчком. Загрузите скрипт установки с веб-сайта приложения, затем запустите его, чтобы установить все необходимые пакеты и саму программу.

После установки начало вечера команда в PanDocElectron каталог запустит приложение. Благодаря выпадающим спискам форматов и возможности выбора входного файла с помощью диалогового окна это поможет вам привыкнуть к «входам и выходам» pandoc.

Если вы знакомы с множеством опций и флагов pandoc, но хотите просто вызов это, вы можете интегрировать его с вашим текстовым редактором GUI. Например, редактор Atom содержит несколько пакетов, которые позволяют сохранить текущий файл в различных форматах с помощью pandoc (пакет pandoc-convert):

Другой вариант — запускать команды pandoc, используя встроенные функции редактора, такие как команда build. атома строить-инструменты Пакет дает вам возможность указать пользовательские команды:

Затем вы можете вызвать команду build для ваших файлов, совместимых с pandoc, так же, как и для исходного кода:

Пандок снимает стресс от переключения

С pandoc в вашем наборе вы можете быть спокойны, зная, что вы всегда можете передать свои документы другим людям в нужном им формате. В то же время вы можете воспользоваться некоторыми из замечательных возможностей Linux (подумайте о предоставлении одного из текстовых редакторов на базе терминала, таких как напор попытка).

Вы часто конвертируете файлы назад и вперед между форматами? Если у вас возникли проблемы с совместимостью, сообщите нам в комментариях, и мы посмотрим, сможем ли мы использовать pandoc, чтобы разобраться с вами!

Источник

Word to text linux

Simple utility for converting a Microsoft Word Document ‘.doc’ and Microsoft Excel ‘.xls’ files to any other supported format such as .txt .csv .rtf .pdf.

Can also be used to convert .txt, .rtf, .csv to .doc, .xls or .pdf format.

Can be used to convert older word documents to latest format.

Must have Microsoft Word or Excel installed on host machine.

Download Release From Github Releases — https://github.com/tobya/DocTo/releases/ Further Information available at https://tobya.github.io/DocTo/ Further Examples available at https://docto.toflidium.com

  1. Convert Doc/RTF/Text file to any Word SaveAs Type Doc/Text/RTF/PDF
  2. Convert XLS/XLSX/CSV file to any Excel SaveAs Type CSV/Text/PDF
  3. Convert Text/CSV file to full fledged Word or Excel format.
  4. Single File Conversion
  5. Multiple / Directory File Conversion.
  6. Delete after conversion
  7. Fire https Webhook on each conversion.

More Examples available at

to upgrade to latest version before generally available (replace with current version)

Node Wrappers has been created by @KerimG & @brrd

Bugs and Features

Please log an issue for any bugs, features or suggestions.

Convert Microsoft Word Document to text

Convert Microsoft Excel Document to csv text

Convert Microsoft Word Document to PDF (requires version of Microsoft Word that supports this).

Multiple Files and Folders

Convert All Microsoft Word Documents in Directory and its Sub Directories to PDF

Delete Original File after Conversion

Delete Original Files after conversion (-R) .

Add a Webhook to fire on each conversion (-W)

A Webhook is a url that can be called on each converstion to give you the ability to repond externally whenever a file is converted. Currently https address is experimental so log an issue if you have any issues.

Use in the Wild

If you are using DocTo in the wild somewhere, please add details to this wiki page

If you need to upgrade a bunch of files to work without conversion on OneDrive /Office365 / Word 20XX then you can use DocTo. See this StackExchange question

Command Line Help

The project compiles with Delphi (I use 10.3 but it should compile with most versions including XE4 & 7). The project will not compile on Linux as it uses several Windows only components such as COM and Word and Excel do not have Linux versions anyway so there would be no point.

XLSTo is now incorporated into DocTo. Previously XLSTo was a seperate EXE that was used to convert xls files to csv or pdf. This can now be done with the main DocTo.exe by simply adding the -XL flag.

I am happy to accept any PR anyone might like to submit. If a large amount of work involved, please open an issue first to ensure the effort wont be wasted.

The main branch name in the repo is DocTo

About

Simple command line utility for converting .doc & .xls files to any supported format such as Text, RTF, CSV or PDF

Источник

Converting .docx files to plain text and preserving line breaks to maintain line number references to source document: howto & implications?

I’m exporting MS Word content to plain text for use with text&file utilities. I have a constraint where the line numbering feature has been enabled in the MS software, and any reference to line numbers in the final output must match that numbering. So enter «numbering lines»:

(Poe, E.A.)

Obviously for Word, that sort of numbering doesn’t break lines at newline, it breaks «lines» after the right margin (or something). A script like docx2txt , doesn’t account for this by default it seems and breaks lines at newline. So if I use grep -n with numbering, the lines won’t match the source line numbers feature, as illustrated above. It’s not exactly clear from the documentation how I would need to edit the Perl script to convert the files the way I need to in this case:

I tried substituting n for rn but that doesn’t seem to work for me. So I resorted to exporting the documents directly from Word with the following settings(save as plain text, on v.2013,64pc):

  • Unicode(UTF-8)
  • Insert line breaks + end lines with (CR/LF)
  • Allow character substitution

And now indeed when I use the .txt files there is a perfect match between line numbers in the source numbering feature and the grep -n output.

  • Is there any specific configuration/process I should know about docx2txt or a similar command line utility which would have allowed me to convert my .docx files to plain text while preserving line breaks, without resorting to Word like I did?
  • What are the best practices, if any, for exporting MS Word documents (which may contain accented characters) to plain text for use with file/text utilities, with respect to line breaks and formatting; and are there any negative implications with the settings I chose for exporting i.e. inserting CR/LF?

As suggested I provide a sample. In this rar archive, I bundled a .docx file with simple paragraphs, and its exported .txt file using Word with the aforementioned options. The latter can be compared with a default run of docx2txt on the source file.

1 Answer 1

docx2txt works on the information in the docx file which is a zipped set of XML files.

With regards to line wrapping the .docx XML data only includes information about paragraphs and hard-breaks, not about soft-breaks. Soft-breaks are a result of rendering the text in a specific font, font-size and page width. docx2txt normally just tries to fit text in 80 columns (80 columns is configurable), without any regard for font and font-size. If your .docx contains font information from a Windows system that is not available on Unix/Linux, then doing the export to .txt via Open/LibreOffice would also unlikely result in the same layout, although it tries to do a good job¹.

So docx2txt or any other commandline utility, including commandline driven Open/LibreOffice processing, will not guaranteed convert the text to the same layout as exporting from Word does².

If you want to (or are forced by client requirements) to render exactly as Word does, there is in my experience only one way: let Word do the rendering. When faced with a similar problem as yours³, and having incompatible results using other tools, including OpenOffice, I reverted to installing a Windows VM on the host Linux server. On the client VM a program observes incoming files to be converted on the host, which would start and drive Word to do the conversion and then copy back the result⁴.

Decisions about using CR/LF or LF only, or UTF-8 or some other encoding for the .txt largely depends on how the resulting files are used. If the resulting files are used on Windows I would definately go with CR/LF, UTF-8 and an UTF-8 BOM. Modern programs on Linux are able to deduce that a file is UTF-8, but will not barf on the BOM and/or use that information. You should test all your target applications for compatibility if those are known up front.

¹ This sort of incompatibility is the primary reason some of my friends cannot change to Linux from Windows, although they would like to. They have to use MicroSoft Word, as Open/LibreOffice every once in a while mangles texts they exchange with clients.
² You can install all the fonts used in the Word files and might get lucky for some texts, some of the time.
³ Rendering PDFs from .doc/.docx
The program uses GUI automation—as if someone is clicking its menus—and doesn’t attempt to drive Word via an API. I am pretty sure the latter can be done as well and would have the advantage of not breaking things if Word would get upgraded

Источник

It can be frustrating when content comes your way in an unreadable format. For instance, if you work at the command line, or have an older version of Microsoft Word, you may have no way to read the contents of a file in Microsoft’s .docx format – unless, that is, you have a tool like docx2txt on your side.

Docx2txt is a Perl-based command-line tool to convert Microsoft .docx documents to ASCII text files, preserving some formatting and document information and performing appropriate character conversions.

Developer Sandeep Kumar says, “Often command-line users like me just need to get the hang of document content. I find it fast and convenient to browse and view files in Midnight Commander. More than an year back, when I first came across files with the extension .docx, it was a mystery, and I couldn’t find an open source, command-line tool for Linux to show me content of these files. Around that time I came across a requirement for a résumé-parsing site that needed to handle .docx résumés as well.” Thus was born docx2txt.

Unlike Microsoft’s Word’s Save As Text feature, docx2txt lets you maintain left, right, or center alignment of text in lines of configurable length, and can keep hyperlinks available. Kumar says, “My focus has been toward generating plain ASCII text content. That’s why at some places I substitute characters with equivalent ASCII characters or character sequence, such as currency symbols replaced by currency names like euro, yen, or cent.”

Because it’s written in Perl, docx2txt can run under Windows as well, or it can serve as a base for a web-based service for extracting text content from docx documents. The script lets you tune its output via a configuration file.

Kumar has a laundry list of features he hopes to implement in future versions, including improved handling of lists and tables, extraction of images, and better documentation. He expects to release new versions two or three times a year. If you have suggestions for additional features for upcoming releases, you can contact Kumar through the project’s SourceForge.net forums and trackers.

docx2txt works on the information in the docx file which is a zipped set of XML files.

With regards to line wrapping the .docx XML data only includes information about paragraphs and hard-breaks, not about soft-breaks. Soft-breaks are a result of rendering the text in a specific font, font-size and page width. docx2txt normally just tries to fit text in 80 columns (80 columns is configurable), without any regard for font and font-size. If your .docx contains font information from a Windows system that is not available on Unix/Linux, then doing the export to .txt via Open/LibreOffice would also unlikely result in the same layout, although it tries to do a good job¹.

So docx2txt or any other commandline utility, including commandline driven Open/LibreOffice processing, will not guaranteed convert the text to the same layout as exporting from Word does².

If you want to (or are forced by client requirements) to render exactly as Word does, there is in my experience only one way: let Word do the rendering. When faced with a similar problem as yours³, and having incompatible results using other tools, including OpenOffice, I reverted to installing a Windows VM on the host Linux server. On the client VM a program observes incoming files to be converted on the host, which would start and drive Word to do the conversion and then copy back the result⁴.

Decisions about using CR/LF or LF only, or UTF-8 or some other encoding for the .txt largely depends on how the resulting files are used. If the resulting files are used on Windows I would definately go with CR/LF, UTF-8 and an UTF-8 BOM. Modern programs on Linux are able to deduce that a file is UTF-8, but will not barf on the BOM and/or use that information. You should test all your target applications for compatibility if those are known up front.

¹ This sort of incompatibility is the primary reason some of my friends cannot change to Linux from Windows, although they would like to. They have to use MicroSoft Word, as Open/LibreOffice every once in a while mangles texts they exchange with clients.
² You can install all the fonts used in the Word files and might get lucky for some texts, some of the time.
³ Rendering PDFs from .doc/.docx
The program uses GUI automation—as if someone is clicking its menus—and doesn’t attempt to drive Word via an API. I am pretty sure the latter can be done as well and would have the advantage of not breaking things if Word would get upgraded

Понравилась статья? Поделить с друзьями:
  • Link in excel will not break
  • Linux ubuntu office word
  • Link forms in word
  • Linux search for a word in a file
  • Link file from excel to word