Офис и PDF
Конвертировать Word в PDF
Пакетно переводит DOC и DOCX в PDF через LibreOffice и не трогает исходники.
Shell
Linux
macOS
Новичок
Что делает скрипт
Скрипт принимает файл или папку, находит документы Word и вызывает soffice в headless режиме. Результаты складываются в отдельную папку, существующие PDF пропускаются без --force. Если LibreOffice не установлен, выводится понятная ошибка.
Запуск
Быстрый старт
bash word_to_pdf.sh --input ./documents
Скачайте файл, откройте терминал в папке со скриптом и выполните команду.
Другие варианты
bash word_to_pdf.sh --input report.docx --outdir pdfbash word_to_pdf.sh --input ./docs --outdir pdf --force
Что понадобится
Bash 4+
Стандартные утилиты find и coreutils
Linux
sudo apt install bash
macOS
brew install bash
LibreOffice
Нужен soffice в PATH
Linux
sudo apt install libreoffice
macOS
brew install --cask libreoffice
Исходник
word_to_pdf.sh
#!/usr/bin/env bash
set -euo pipefail
usage() {
echo "Использование: $0 --input <файл или папка> [--outdir <папка>] [--force]"
}
input=""
outdir="converted"
force=0
while [[ $# -gt 0 ]]; do
case "$1" in
--input) input="${2:-}"; shift 2 ;;
--outdir) outdir="${2:-}"; shift 2 ;;
--force) force=1; shift ;;
-h|--help) usage; exit 0 ;;
*) echo "Неизвестный аргумент: $1" >&2; usage >&2; exit 2 ;;
esac
done
if [[ -z "$input" || ! -e "$input" ]]; then
echo "Укажите существующий файл или папку через --input" >&2
exit 2
fi
find_soffice() {
if [[ -n "${SOFFICE_BIN:-}" && -x "${SOFFICE_BIN}" ]]; then
printf '%s\n' "$SOFFICE_BIN"
return 0
fi
local candidate
for candidate in soffice libreoffice; do
if command -v "$candidate" >/dev/null 2>&1; then
command -v "$candidate"
return 0
fi
done
for candidate in "/Applications/LibreOffice.app/Contents/MacOS/soffice" "/usr/lib/libreoffice/program/soffice"; do
if [[ -x "$candidate" ]]; then
printf '%s\n' "$candidate"
return 0
fi
done
return 1
}
soffice_bin="$(find_soffice || true)"
if [[ -z "$soffice_bin" ]]; then
echo "LibreOffice не найден. Установите soffice и повторите запуск." >&2
exit 2
fi
files=()
if [[ -f "$input" ]]; then
files+=("$input")
elif [[ -d "$input" ]]; then
while IFS= read -r -d '' file; do
files+=("$file")
done < <(find "$input" -type f \( -iname '*.docx' -o -iname '*.doc' \) -print0)
else
echo "Путь не является файлом или папкой: $input" >&2
exit 2
fi
if [[ ${#files[@]} -eq 0 ]]; then
echo "Документы Word не найдены" >&2
exit 1
fi
mkdir -p "$outdir"
converted=0
failed=0
for source in "${files[@]}"; do
name="$(basename "${source%.*}")"
target="$outdir/$name.pdf"
if [[ -e "$target" && "$force" -eq 0 ]]; then
echo "Пропуск, уже существует: $target"
continue
fi
"$soffice_bin" --headless --convert-to pdf --outdir "$outdir" "$source" >/dev/null 2>&1 || true
if [[ -f "$target" ]]; then
echo "Готово: $target"
converted=$((converted + 1))
else
echo "Не удалось конвертировать: $source" >&2
failed=$((failed + 1))
fi
done
echo "Сконвертировано файлов: $converted, ошибок: $failed"
[[ "$failed" -eq 0 ]]
Скрипты работают с файлами и настройками системы. Перед запуском прочитайте код и проверьте пути. Особенно если скрипт удаляет, перезаписывает или перемещает данные.