Libreoffice linux command line

Работа LibreOffice в командной строке: конвертирование большого количества файлов и вывод содержимого офисных файлов в консоль

Работа в консоли, если вы в этом разбираетесь, может увеличить вашу производительность. Особенно если это касается большого количества однотипных задач.

Предположим, нам дано множество офисных файлов в формате .doc (или любом другом формате, который поддерживает LibreOffice), и мы хотим их переконвертировать в другой формат. Если файлов немного, то их можно открыть в LibreOffice и выбрать сохранение в нужном формате. Но если их десятки и более, то эта рутинная работа станет долгой и утомительной.

К счастью, LibreOffice умеет работать в консоли. Причём нам даже не нужно писать скрипты, поскольку она понимает подстановочные символы.

Сохранение большого количества файлов в другой формат

Для этого нужно запустить команду

soffice --headless --convert-to doc Имя_файла
  • doc – можно заменить на желаемый формат (pdf, html, odt, docx и т.д.)
  • Имя_файла – замените на тот файл, который вы хотите конвертировать.

Конвертирует все поддерживаемые файлы в каталоге Математика в html формат и сохранит их в текущем каталоге^

soffice --headless --convert-to html Математика/*

Конвертировать все файлы в формате .doc в формат PDF и сохранить их в каталоге /home/user:

soffice --headless --convert-to pdf:writer_pdf_Export --outdir /home/user *.doc

Конвертировать все файлы в формате .doc в формат html с кодировкой UTF8 и сохранить их в текущем каталоге.

soffice --headless --convert-to "html:XHTML Writer File:UTF8" *.doc

Конвертировать все файлы в формате .doc в обычный текст с кодировкой UTF8.

soffice --headless --convert-to "txt:Text (encoded):UTF8" *.doc

Вывод содержимого файла в консоль

Иногда нужно, чтобы консольный Bash скрипт прочитал содержимое офисного файла и вывел это содержимое в консоль. Если бы нас интересовали обычные текстовые файлы, то мы могли бы воспользоваться командой cat. Но офисные файлы имеют сложную структуру и иногда представляют собой архивы, т.е. бинарные файлы. Поэтому для этого у LibreOffice есть специальная опция командной строки —cat:

soffice --headless --cat имя_файла

Конечно, сложные элементы, которые не могут быть отображены в командной строке (картинки, формы и т.д.), показаны не будут.

Связанные статьи:

Рекомендуемые статьи:

12 Комментарии

А в винде команда конвертации недоступна? я могу открыть командой файл, но конвертироваться он не желает.
Пробовал разные варианты. С конкретным фалом, со всеми файлами в папке, конвертацию в разные фрматы, даже запуск в самом ридере swriter.exe с параметрами. В итоге все равно открывается, но не конвертится. Винда не может в последовательность команд ? Секретного варианта запуска и исполнения макроса, как в ворде, нету?

Читайте также:  Mediatek linux wifi driver

Там в одном примере даже зачем-то PS приплели.

В общем, проблема решилась с помощью Cygwin:

'C:/Program Files/LibreOffice 5/program/soffice.bin' --headless --convert-to pdf:writer_pdf_Export --outdir 'C:\tmp' 'C:\1.docx' convert C:\1.docx -> C:\tmp\1.pdf using filter : writer_pdf_Export

Т.е. в Cygwin я запускал файл soffice.bin. У Cygwin сразу два огромных плюса:

  • он выводит ошибки (это помогло мне узнать, что LibreOffice не может прочитать исходный файл)
  • можно использовать подстановочные символы (в командной строке Windows никакие бы звёздочки мы не смогли использовать, пришлось бы писать простой bat скрипт для автоматизации).
Batch convert files. If --outdir is not specified, then current working directory is used as output_dir.

обязательно нужно указывать оба параметра, ибо папка выхода сама не прописывается. Да, то что cmd ошибки не выводит это… раздражает Но в принципе

"C:\Program Files\LibreOffice 5\program\soffice.exe" --headless --convert-to pdf:writer_pdf_Export --outdir "C:\tmp" "C:\tmp\1.docx"

так запускается и отрабатывает даже в обычной cmd. PS Реадктор огонь, но… как вставлять в стиле кода?)

В стиле кода только для админа, причём только из админки при редактировании комментария – здесь даже я не могу вставить Это связано с фильтрацией данных (тегов).

"C:\Program Files\LibreOffice 5\program\soffice.exe" --headless --convert-to docx --outdir C:\Clip\Anton C:\Clip\Anton\Обзор ВП сентябрь 2019.doc
"C:\Program Files\LibreOffice 5\program\soffice.exe" --headless --convert-to docx --outdir "C:\Clip\Anton\Обзор ВП сентябрь 2019.doc"

Подскажите комманду для извлечения изображений из PDF-файла. То есть для каждой страницы PDF файла на выходе получается 1 картинка (jpg,png).

Добрый день! Не работает пакетная обработка, не пойму почему. soffice —headless —convert-to docx —outdir d:\doc\d2 d:\doc\d1\*.doc Error: source file could not be loaded а один файл работает soffice —headless —convert-to docx —outdir d:\doc\d2 d:\doc\d1\1.doc

Windows 10, LibreOffice 6.4, надо PDF во что-либо другое — не работает.
Уже и полные пути прописывал, и разные форматы пробовал — команда просто молча уходит в никуда.
Никаких ошибок, ни на что не ругается, просто пустота.
Пару раз появился пустой HTML-файл, и тот через минуту после команды.

Возможно, конвертировать можно только родные форматы. Что касается PDF, то такие файлы Writer даже не умеет открывать. Из пакета LibreOffice такие файлы умеет открывать только Draw, но эта программа может сохранить только в свой родной формат. В общем, вы выбрали неверный инструмент. FineReader умеет конвертировать PDF во что угодно. Причём PDF бывают двух видов — с текстовым слоем и без. Если текстовый слой есть, то его можно сохранить из любой программы для просмотра PDF. Если текстового слоя нет, то кроме OCR (программы для распознавания текста) никто его сохранить в текст не сможет. Максимум что можно сделать с таким файлом — это разбить на отдельные изображения. Возможно, FineReader поддерживает работу в командной строке, если вам нужно именно это. А так там очень удобно перетаскивать PDF прямо в программу и она его распознает и сохранит.

Читайте также:  Проверка установленного пакета linux

Источник

libreoffice — Man Page

libreoffice [—accept=accept-string] [—base] [—calc] [—convert-to output_file_extension[:output_filter_name] [—outdir output_dir] file]. [—display display] [—draw] [—global] [—headless] [—help|-h|-?] [—impress] [—invisible] [—infilter=»»] [—math] [—minimized] [-n file]. [—nodefault] [—nolockcheck] [—nologo] [—norestore] [-o file]. [-p file. ] [—print-to-file [—printer-name printer_name] [—outdir output_dir] file]. [—pt printername file. ] [—show Impress file]. [—unaccept=accept-string] [—terminate_after_init] [—view file]. [—web] [—writer] [file. ]
lobase
localc
lodraw
lofromtemplate
loimpress
lomath
loweb
lowriter

Description

LibreOffice (LO for short) is a multi-platform office productivity suite. It was derived from OpenOffice.org 3.3 Beta on September 28, 2010.

libreoffice is a shell script that sets up the environment and passes the command line arguments to the soffice.bin binary.

Alternatively, the following helper scripts start the respective module:

sbase, scalc, sdraw, simpress, smath, sofficerc, swriter

Options

Specifies a UNO-URL connect-string to create a UNO acceptor through which other programs can connect to access the API. Note that API access allows execution of arbitrary commands. The syntax of a UNO-URL connect-string is: uno:connection-type,params;protocol-name,params;ObjectName

Starts the wizard for a new Base document.

Starts with a new Calc document.

—convert-to output_file_extension[:output_filter_name] [—outdir output_dir] file.

Batch converts files. If —outdir is not specified then the current working directory is used as the output directory for the converted files. It implies —headless.

Converts all .doc files to PDFs.

—convert-to pdf:writer_pdf_Export —outdir /home/user *.doc

Converts all .doc files to PDFs using the settings in the Writer PDF export dialog and saving them in /home/user.

This option specifies the X server to use; see X(7)

Starts with a new Draw document.

Starts with a new Global document.

Starts in «headless mode», which allows using the application without user a interface.

This special mode can be used when the application is controlled by external clients via the API.

It implies —invisible and strictly ignores any GUI environment. —quickstart does not work with this parameter.

Lists LibreOffice command line parameters.

Starts with a new Impress document.

Neither the start-up logo nor the initial program window will be visible. LO can be controlled and documents and dialogs can be opened via the API.

When started with this parameter, it can only be quit using the taskmanager (Windows) or the kill command (UNIX based systems).

—quickstart does not work with this parameter.

Force an input filter type if possible. For example —infilter=»Calc Office Open XML» only

Читайте также:  How to install glew linux

Starts with a new Math document.

Keeps the splash screen minimized.

Creates the a new document from the given templates.

Starts LO without creating a new document. The next time you start LO, the welcome screen is shown.

It’s used together with —nologo by quick starters. Note that —quickstart has no longer been supported since OpenOffice.org 2.0.0.

Disables the check for remote instances using the installation.

Disables the splash screen at program start.

Disables restart and file recovery after a system crash. It is possible that LO will try to restore a file it keeps crashing on, if that happens —norestore is the only way to start LO.

Disables the splash screen at program start.

Opens the given files for editing, even templates.

Without -o a template file would create a new document derived from that template.

Prints the given files to the default printer and ends. The splash screen does not appear.

If the file name contains spaces, then it must be enclosed in quotation marks.

Batch print files to file. If —printer-name is not specified the default printer is used. If —outdir is not specified then the current working directory is used as the output directory for the converted files.

Prints all .doc files to the current working directory using the default printer.

Prints all .doc files to /home/user directory using the nasty_lowres_printer.

Prints the given files to the printer printername and ends. The splash screen does not appear.

If a file name contains spaces, then it must be enclosed in quotation marks.

Starts LO with its quick starter. —quickstart disable the quick starter.

Does not work with —invisible or —headless.

Opens the given Impress files, starts the presentation and quits after they have finished.

Closes an acceptor that was created with —accept option.

Use —unaccept=all to close all open acceptors.

Starts LO and terminates after it registers some UNO services. Doesn’t show the splash during startup.

Opens the given files read-only creating a temporary copy of them at $TMPDIR.

Starts with a new HTML document.

Starts with a new Writer document.

Troubleshooting Problems

See http://wiki.documentfoundation.org/BugReport for more details on how to report bugs in LibreOffice.

See Also

Author

This manual page was created by Rene Engelhard for the Debian GNU/Linux Distribution, because the original package does not have one. It was updated for Novell by Petr Mladek and adapted for LibreOffice by Philipp Weissenbacher .

Referenced By

The man pages oobase(1), oocalc(1), oodraw(1), ooffice(1), ooimpress(1), oomath(1), ooviewdoc(1), oowriter(1), openoffice.org(1) and soffice(1) are aliases of libreoffice(1).

Источник

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