Офис и PDF

Собрать PDF из изображений

Склеивает PNG и JPEG в один PDF, сохраняя порядок и учитывая поворот EXIF.

Python Windows macOS Linux Новичок
Скачать images_to_pdf.py
Описание

Что делает скрипт

Скрипт принимает список файлов или папку с изображениями, приводит их к RGB и сохраняет многостраничный PDF. Поворот из EXIF применяется автоматически, прозрачность заменяется белым фоном. Разрешение страниц можно задать через --dpi.

Запуск

Быстрый старт

python images_to_pdf.py -o album.pdf photo1.jpg photo2.png

Скачайте файл, откройте терминал в папке со скриптом и выполните команду. В Linux и macOS интерпретатор может называться python3, в Windows - python или py.

Примеры

Другие варианты

  • python images_to_pdf.py -o scans.pdf --dir ./scans --dpi 200
  • python images_to_pdf.py -o book.pdf page1.png page2.png --force
Зависимости

Что понадобится

Python 3.10+ Интерпретатор и стандартная библиотека
Windows winget install Python.Python.3.12
macOS brew install python
Linux sudo apt install python3
Pillow
Windows py -m pip install Pillow
macOS python3 -m pip install Pillow
Linux python3 -m pip install Pillow
Исходник

images_to_pdf.py

#!/usr/bin/env python3
"""Сборка PDF из набора изображений."""
from __future__ import annotations

import argparse
import sys
from pathlib import Path

from PIL import Image, ImageOps

EXTENSIONS = {".png", ".jpg", ".jpeg", ".bmp", ".tif", ".tiff", ".webp"}


def load_image(path: Path) -> Image.Image:
    with Image.open(path) as source:
        image = ImageOps.exif_transpose(source)
        if image.mode in ("RGBA", "LA"):
            background = Image.new("RGB", image.size, "white")
            alpha = image.getchannel("A")
            background.paste(image, mask=alpha)
            return background
        if image.mode != "RGB":
            return image.convert("RGB")
        return image.copy()


def collect(paths: list[Path], directory: Path | None) -> list[Path]:
    files: list[Path] = []
    if directory:
        folder = directory.expanduser()
        if not folder.is_dir():
            raise ValueError(f"Папка не найдена: {folder}")
        files.extend(sorted(item for item in folder.iterdir() if item.is_file() and item.suffix.lower() in EXTENSIONS))
    for item in paths:
        path = item.expanduser()
        if path.is_file() and path.suffix.lower() in EXTENSIONS:
            files.append(path)
        else:
            print(f"Пропуск, это не изображение: {path}", file=sys.stderr)
    seen: set[Path] = set()
    unique: list[Path] = []
    for item in files:
        resolved = item.resolve()
        if resolved not in seen:
            seen.add(resolved)
            unique.append(item)
    return unique


def main() -> int:
    parser = argparse.ArgumentParser(description="Собрать PDF из изображений")
    parser.add_argument("images", nargs="*", type=Path, help="Файлы изображений")
    parser.add_argument("--dir", type=Path, help="Папка с изображениями")
    parser.add_argument("-o", "--output", type=Path, required=True, help="Итоговый PDF")
    parser.add_argument("--dpi", type=int, default=150, help="Разрешение страниц")
    parser.add_argument("--force", action="store_true", help="Перезаписать итоговый файл")
    args = parser.parse_args()

    output = args.output.expanduser()
    if output.suffix.lower() != ".pdf":
        print("Итоговый файл должен иметь расширение .pdf", file=sys.stderr)
        return 2
    if output.exists() and not args.force:
        print(f"Файл уже существует: {output}. Добавьте --force.", file=sys.stderr)
        return 2

    try:
        files = collect(args.images, args.dir)
    except ValueError as error:
        print(error, file=sys.stderr)
        return 2
    if not files:
        print("Не найдено ни одного изображения", file=sys.stderr)
        return 2

    images: list[Image.Image] = []
    try:
        for path in files:
            try:
                images.append(load_image(path))
            except Exception as error:
                print(f"Пропуск {path}: {error}", file=sys.stderr)
        if not images:
            print("Не удалось прочитать изображения", file=sys.stderr)
            return 1
        output.parent.mkdir(parents=True, exist_ok=True)
        first, rest = images[0], images[1:]
        first.save(output, "PDF", resolution=args.dpi, save_all=True, append_images=rest)
    finally:
        for image in images:
            image.close()

    print(f"Готово: {output}, страниц: {len(images)}")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())

Скрипты работают с файлами и настройками системы. Перед запуском прочитайте код и проверьте пути. Особенно если скрипт удаляет, перезаписывает или перемещает данные.

CLI 1.0.0

Скачать без браузера

Команда скачает этот файл в текущую папку. CLI работает на Windows, macOS и Linux.

scriptdock get office-images-to-pdf
  • Поиск по всему каталогу
  • Python 3.10+
  • Без внешних пакетов
Скачать CLI

GUI-версия готовится. Подробнее

Категория

Офис и PDF

PDF, Word, Excel, презентации, документы и печать.