Skip to content

Commit

Permalink
ENH: Add decryption to the cat operation (#61)
Browse files Browse the repository at this point in the history
* Allow decryption by adding an optional password parameter to the "cat" operation
* Make decryption errors more readable for end-users
  • Loading branch information
EmperorArthur authored Dec 8, 2024
1 parent 00356c0 commit a18ae8a
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 2 deletions.
10 changes: 9 additions & 1 deletion pdfly/cat.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,9 +46,10 @@
import sys
import traceback
from pathlib import Path
from typing import List, Tuple
from typing import List, Optional, Tuple

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


def main(
Expand All @@ -57,6 +58,7 @@ def main(
output: Path,
verbose: bool,
inverted_page_selection: bool = False,
password: Optional[str] = None,
) -> None:
filename_page_ranges = parse_filepaths_and_pagerange_args(
filename, fn_pgrgs
Expand All @@ -77,6 +79,8 @@ def main(
in_fs[filepath] = open(filepath, "rb")

reader = PdfReader(in_fs[filepath])
if password is not None:
reader.decrypt(password)
num_pages = len(reader.pages)
start, end, step = page_range.indices(num_pages)
if (
Expand All @@ -100,6 +104,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 @@ -95,8 +95,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=password)


@entry_point.command(name="booklet", help=pdfly.booklet.__doc__) # type: ignore[misc]
Expand Down

0 comments on commit a18ae8a

Please sign in to comment.