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

ENH: Add decryption to the cat operation #61

Merged
merged 6 commits into from
Dec 8, 2024
Merged
Show file tree
Hide file tree
Changes from 2 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 @@ -46,9 +46,10 @@
import sys
import traceback
from pathlib import Path
from typing import List, Tuple
from typing import List, Tuple, Optional
MartinThoma marked this conversation as resolved.
Show resolved Hide resolved

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
MartinThoma marked this conversation as resolved.
Show resolved Hide resolved
) -> None:
filename_page_ranges = parse_filepaths_and_pagerange_args(
filename, fn_pgrgs
Expand All @@ -76,7 +78,9 @@ def main(
if filepath not in in_fs:
in_fs[filepath] = open(filepath, "rb")

reader = PdfReader(in_fs[filepath])
reader = PdfReader(in_fs[filename])
MartinThoma marked this conversation as resolved.
Show resolved Hide resolved
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)
MartinThoma marked this conversation as resolved.
Show resolved Hide resolved


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