99 lines
2.9 KiB
Python
99 lines
2.9 KiB
Python
"""PDF utilities."""
|
|
|
|
import subprocess
|
|
from pathlib import Path
|
|
|
|
import click
|
|
|
|
from mycli.utils import handle_errors, run_command
|
|
|
|
|
|
@click.group()
|
|
def pdf():
|
|
"""PDF manipulation commands."""
|
|
pass
|
|
|
|
|
|
@pdf.command("compress")
|
|
@click.argument("files", nargs=-1, required=True)
|
|
@click.option(
|
|
"--quality",
|
|
"-q",
|
|
type=click.Choice(["screen", "ebook", "printer", "prepress"]),
|
|
default="screen",
|
|
help="Compression quality level",
|
|
)
|
|
@click.option("--dry-run", "-n", is_flag=True, help="Show what would be done")
|
|
@handle_errors
|
|
def compress(files, quality, dry_run):
|
|
"""Compress PDF files using ghostscript."""
|
|
for pattern in files:
|
|
for pdf_file in Path(".").glob(pattern):
|
|
if pdf_file.suffix.lower() != ".pdf":
|
|
continue
|
|
|
|
output = pdf_file.with_suffix(".compressed.pdf")
|
|
cmd = [
|
|
"gs",
|
|
"-sDEVICE=pdfwrite",
|
|
"-dNOPAUSE",
|
|
"-dQUIET",
|
|
"-dBATCH",
|
|
f"-dPDFSETTINGS=/{quality}",
|
|
"-dCompatibilityLevel=1.4",
|
|
f"-sOutputFile={output}",
|
|
str(pdf_file),
|
|
]
|
|
|
|
if dry_run:
|
|
click.echo(f"Would compress: {pdf_file} -> {output}")
|
|
continue
|
|
|
|
click.echo(f"Compressing: {pdf_file}")
|
|
run_command(cmd, check=True)
|
|
output.replace(pdf_file)
|
|
click.echo(f" Done: {pdf_file}")
|
|
|
|
|
|
@pdf.command("crop")
|
|
@click.argument("files", nargs=-1, required=True)
|
|
@click.option("--dry-run", "-n", is_flag=True, help="Show what would be done")
|
|
@handle_errors
|
|
def crop(files, dry_run):
|
|
"""Crop PDF files."""
|
|
for pattern in files:
|
|
for pdf_file in Path(".").glob(pattern):
|
|
if pdf_file.suffix.lower() != ".pdf":
|
|
continue
|
|
|
|
if dry_run:
|
|
click.echo(f"Would crop: {pdf_file}")
|
|
continue
|
|
|
|
click.echo(f"Cropping: {pdf_file}")
|
|
run_command(["pdfcrop", str(pdf_file), str(pdf_file)], check=False)
|
|
|
|
|
|
@pdf.command("to-tiff")
|
|
@click.argument("files", nargs=-1, required=True)
|
|
@click.option("--density", "-d", default="300", help="DPI density")
|
|
@click.option("--dry-run", "-n", is_flag=True, help="Show what would be done")
|
|
@handle_errors
|
|
def to_tiff(files, density, dry_run):
|
|
"""Convert PDF to TIFF."""
|
|
for pattern in files:
|
|
for pdf_file in Path(".").glob(pattern):
|
|
if pdf_file.suffix.lower() != ".pdf":
|
|
continue
|
|
output = pdf_file.with_suffix(".tiff")
|
|
|
|
if dry_run:
|
|
click.echo(f"Would convert: {pdf_file} -> {output}")
|
|
continue
|
|
|
|
click.echo(f"Converting: {pdf_file} -> {output}")
|
|
run_command(
|
|
["convert", "-density", density, str(pdf_file), "-compress", "zip", str(output)],
|
|
check=False,
|
|
)
|