-
Notifications
You must be signed in to change notification settings - Fork 23
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
Implement uncompress functionality for PDF files #75
Merged
Merged
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
0b4b4b7
Add requested changes 1
Kaos599 85a9e26
Added uncompress comand to README & Unit tests for uncompress.py
Kaos599 e263a30
Fixed Black linting
Kaos599 4110a43
fixed black 2
Kaos599 dfa139a
fixed black 2
Kaos599 1806128
Pleasing black
Lucas-C 32c4ec0
Pleasing ruff
Lucas-C File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change | ||
---|---|---|---|---|
|
@@ -16,6 +16,7 @@ | |||
import pdfly.metadata | ||||
import pdfly.pagemeta | ||||
import pdfly.rm | ||||
import pdfly.uncompress | ||||
import pdfly.up2 | ||||
import pdfly.update_offsets | ||||
import pdfly.x2pdf | ||||
|
@@ -205,6 +206,30 @@ def compress( | |||
pdfly.compress.main(pdf, output) | ||||
|
||||
|
||||
@entry_point.command(name="uncompress", help=pdfly.uncompress.__doc__) # type: ignore[misc] | ||||
def uncompress( | ||||
pdf: Annotated[ | ||||
Path, | ||||
typer.Argument( | ||||
exists=True, | ||||
file_okay=True, | ||||
dir_okay=False, | ||||
writable=False, | ||||
readable=True, | ||||
resolve_path=True, | ||||
), | ||||
], | ||||
output: Annotated[ | ||||
Path, | ||||
typer.Argument( | ||||
exists=False, | ||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
It can be really useful to override an existing file, I'm not sure this check is needed. |
||||
writable=True, | ||||
), | ||||
], | ||||
) -> None: | ||||
pdfly.uncompress.main(pdf, output) | ||||
|
||||
|
||||
@entry_point.command(name="update-offsets", help=pdfly.update_offsets.__doc__) # type: ignore[misc] | ||||
def update_offsets( | ||||
file_in: Annotated[ | ||||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,52 @@ | ||
"""Module for uncompressing PDF content streams.""" | ||
|
||
import zlib | ||
from pathlib import Path | ||
from typing import Optional | ||
|
||
from pypdf import PdfReader, PdfWriter | ||
from pypdf.generic import IndirectObject, PdfObject | ||
|
||
|
||
def main(pdf: Path, output: Path) -> None: | ||
reader = PdfReader(pdf) | ||
writer = PdfWriter() | ||
|
||
for page in reader.pages: | ||
if "/Contents" in page: | ||
contents: Optional[PdfObject] = page["/Contents"] | ||
if isinstance(contents, IndirectObject): | ||
contents = contents.get_object() | ||
if contents is not None: | ||
if isinstance(contents, list): | ||
for content in contents: | ||
if isinstance(content, IndirectObject): | ||
decompress_content_stream(content) | ||
elif isinstance(contents, IndirectObject): | ||
decompress_content_stream(contents) | ||
writer.add_page(page) | ||
|
||
with open(output, "wb") as fp: | ||
writer.write(fp) | ||
|
||
orig_size = pdf.stat().st_size | ||
uncomp_size = output.stat().st_size | ||
|
||
print(f"Original Size : {orig_size:,}") | ||
print( | ||
f"Uncompressed Size: {uncomp_size:,} ({(uncomp_size / orig_size) * 100:.1f}% of original)" | ||
) | ||
|
||
|
||
def decompress_content_stream(content: IndirectObject) -> None: | ||
"""Decompress a content stream if it uses FlateDecode.""" | ||
if content.get("/Filter") == "/FlateDecode": | ||
try: | ||
compressed_data = content.get_data() | ||
uncompressed_data = zlib.decompress(compressed_data) | ||
content.set_data(uncompressed_data) | ||
del content["/Filter"] | ||
except zlib.error as error: | ||
print( | ||
f"Some content stream with /FlateDecode failed to be decompressed: {error}" | ||
) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,5 +1,3 @@ | ||
import pytest | ||
|
||
from .conftest import RESOURCES_ROOT, chdir, run_cli | ||
|
||
|
||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,40 @@ | ||
"""Tests for the `uncompress` command.""" | ||
|
||
from pathlib import Path | ||
|
||
import pytest | ||
from pypdf import PdfReader | ||
from typer.testing import CliRunner | ||
|
||
from pdfly.cli import entry_point | ||
|
||
runner = CliRunner() | ||
|
||
|
||
@pytest.mark.parametrize( | ||
"input_pdf_filepath", Path("sample-files").glob("*.pdf") | ||
) | ||
def test_uncompress_all_sample_files( | ||
input_pdf_filepath: Path, tmp_path: Path | ||
) -> None: | ||
output_pdf_filepath = tmp_path / "uncompressed_output.pdf" | ||
|
||
result = runner.invoke( | ||
entry_point, | ||
["uncompress", str(input_pdf_filepath), str(output_pdf_filepath)], | ||
) | ||
|
||
assert ( | ||
result.exit_code == 0 | ||
), f"Error in uncompressing {input_pdf_filepath}: {result.output}" | ||
assert ( | ||
output_pdf_filepath.exists() | ||
), f"Output PDF {output_pdf_filepath} does not exist." | ||
|
||
reader = PdfReader(str(output_pdf_filepath)) | ||
for page in reader.pages: | ||
contents = page.get("/Contents") | ||
if contents: | ||
assert ( | ||
"/Filter" not in contents | ||
), "Content stream is still compressed" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Removing the parameters provided that are identical to the default values: https://github.com/fastapi/typer/blob/master/typer/params.py#L301