Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add decryption to the cat operation #61

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 10 additions & 2 deletions pdfly/cat.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,13 +47,14 @@
import sys
import traceback
from pathlib import Path
from typing import List, Tuple
from typing import List, Tuple, Optional

from pypdf import PageRange, PdfReader, PdfWriter, parse_filename_page_ranges
from pypdf.errors import FileNotDecryptedError


def main(
filename: Path, fn_pgrgs: List[str], output: Path, verbose: bool
filename: Path, fn_pgrgs: List[str], output: Optional[Path], verbose: bool, password: Optional[str] = None
) -> None:
filename_page_ranges = parse_filepaths_and_pagerange_args(
filename, fn_pgrgs
Expand All @@ -74,6 +75,9 @@ def main(
in_fs[filename] = open(filename, "rb")

reader = PdfReader(in_fs[filename])
if password is not None:
reader.decrypt(password)

num_pages = len(reader.pages)
start, end, step = page_range.indices(num_pages)
if (
Expand All @@ -90,6 +94,10 @@ def main(
for page_num in range(*page_range.indices(len(reader.pages))):
writer.add_page(reader.pages[page_num])
writer.write(output_fh)
except FileNotDecryptedError as error:
print(str(error), file=sys.stderr)
print(f"Error while reading {filename}", file=sys.stderr)
sys.exit(1)
except Exception:
print(traceback.format_exc(), file=sys.stderr)
print(f"Error while reading {filename}", file=sys.stderr)
Expand Down
5 changes: 4 additions & 1 deletion pdfly/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,8 +99,11 @@ def cat(
verbose: bool = typer.Option(
False, help="show page ranges as they are being read"
),
password: str = typer.Option(
None, help="Document's user or owner password."
),
) -> None:
pdfly.cat.main(filename, fn_pgrgs, output, verbose)
pdfly.cat.main(filename, fn_pgrgs, output, verbose, password)


@entry_point.command(name="meta") # type: ignore[misc]
Expand Down
Loading