-
Notifications
You must be signed in to change notification settings - Fork 1.5k
ENH: Add support for BrotliDecode filter (PDF 2.0) #3223 #3254
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
Open
ash01ish
wants to merge
27
commits into
py-pdf:main
Choose a base branch
from
ash01ish:feat/add-brotli-decode
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 24 commits
Commits
Show all changes
27 commits
Select commit
Hold shift + click to select a range
025226a
ENH: Add support for BrotliDecode filter (PDF 2.0) #3223
ash01ish 97fc4a4
STY: Slightly increase readability (#3098)
j-t-1 7da38f1
BUG: Get font information more reliably when removing text (#3252)
samuelbradshaw 5b7ac7e
MAINT: Modify some comments (#3256)
j-t-1 50c230d
STY: Remove variable check_crlf_space (#3096)
j-t-1 42b9efe
MAINT: Remove an unused variable and zero from the start of slices (#…
j-t-1 2d03292
MAINT: Tweak comments (#3257)
j-t-1 9c064d3
BUG: T* 2D Translation consistent with PDF 1.7 Spec (#3250)
hackowitz-af cbbea23
STY: Remove variable check_crlf_space (#3096)
j-t-1 3ba2235
update changes as suggested
ash01ish 7dcd2e9
Merge branch 'main' into feat/add-brotli-decode
ash01ish 3935ea2
Update test_text_extraction.py
ash01ish b4ac3d9
Update test_filters.py
ash01ish 666b871
Update test_filters.py
ash01ish 48cee95
remove unused imports
ash01ish 94b6485
change import error test case
ash01ish 9b8b80a
fix code fmt
ash01ish e099ead
improve as per suggestions.
ash01ish ab1c492
fix code fmt
ash01ish dc2b4db
remove whitespace
ash01ish fd842b3
Merge branch 'main' into feat/add-brotli-decode
ash01ish 1016c29
Update test_filters.py
ash01ish b0bf326
Merge branch 'main' into feat/add-brotli-decode
ash01ish f143805
fix code fmt issues
ash01ish be1e754
Add decompression bomb protection to BrotliDecode filter
ash01ish c5071a4
Merge branch 'main' into feat/add-brotli-decode
ash01ish 7723cf6
fix: resolve ruff linting errors
ash01ish 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
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or 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 hidden or 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 |
|---|---|---|
|
|
@@ -72,6 +72,11 @@ | |
| is_null_or_none, | ||
| ) | ||
|
|
||
| try: | ||
| import brotli | ||
| except ImportError: | ||
| brotli = None | ||
|
|
||
|
|
||
| def decompress(data: bytes) -> bytes: | ||
| """ | ||
|
|
@@ -513,6 +518,68 @@ | |
| return data | ||
|
|
||
|
|
||
| class BrotliDecode: | ||
| """ | ||
| Decompress the given data using Brotli. | ||
|
|
||
| Decodes data that has been encoded using the Brotli compression algorithm. | ||
| Brotli is a general-purpose lossless compression algorithm that combines | ||
| LZ77 and Huffman coding. It typically achieves better compression ratios | ||
| than Flate encoding, though with slightly slower compression speeds. | ||
|
|
||
| See ISO 32000-2:2020, Section 7.4.11. | ||
|
|
||
| Args: | ||
| data: The input data to be decompressed. | ||
| decode_parms: Optional decoding parameters (currently unused). | ||
| **kwargs: Additional keyword arguments (currently unused). | ||
|
|
||
| Returns: | ||
| The decompressed data. | ||
| """ | ||
| @staticmethod | ||
| def decode( | ||
| data: bytes, | ||
| decode_parms: Optional[DictionaryObject] = None, | ||
| **kwargs: Any, | ||
| ) -> bytes: | ||
| """ | ||
| Decode Brotli-compressed data. | ||
|
|
||
| Args: | ||
| data: Brotli-compressed data. | ||
| decode_parms: A dictionary of parameter values (unused). | ||
|
|
||
| Returns: | ||
| The decompressed data. | ||
|
|
||
| Raises: | ||
| ImportError: If the 'brotli' library is not installed. | ||
| """ | ||
| if brotli is None: | ||
| raise ImportError("Brotli library not installed. Required for BrotliDecode filter.") | ||
| return brotli.decompress(data) | ||
|
||
|
|
||
| @staticmethod | ||
| def encode(data: bytes, **kwargs: Any) -> bytes: | ||
| """ | ||
| Encode data using Brotli compression. | ||
|
|
||
| Args: | ||
| data: The data to be compressed. | ||
| **kwargs: Additional keyword arguments (unused). | ||
|
|
||
| Returns: | ||
| The compressed data. | ||
|
|
||
| Raises: | ||
| ImportError: If the 'brotli' library is not installed. | ||
| """ | ||
| if brotli is None: | ||
| raise ImportError("Brotli library not installed. Required for BrotliDecode filter.") | ||
ash01ish marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| return brotli.compress(data) | ||
|
|
||
|
|
||
| @dataclass | ||
| class CCITTParameters: | ||
| """§7.4.6, optional parameters for the CCITTFaxDecode filter.""" | ||
|
|
@@ -759,6 +826,8 @@ | |
| data = DCTDecode.decode(data) | ||
| elif filter_name == FT.JPX_DECODE: | ||
| data = JPXDecode.decode(data) | ||
| elif filter_name == FT.BROTLI_DECODE: | ||
| data = BrotliDecode.decode(data) | ||
| elif filter_name == FT.JBIG2_DECODE: | ||
| data = JBIG2Decode.decode(data, params) | ||
| elif filter_name == "/Crypt": | ||
|
|
||
This file contains hidden or 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 hidden or 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 hidden or 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 |
|---|---|---|
|
|
@@ -13,3 +13,4 @@ pytest-cov | |
| typeguard | ||
| types-Pillow | ||
| pyyaml | ||
| brotli | ||
This file contains hidden or 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 hidden or 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 |
|---|---|---|
|
|
@@ -4,3 +4,4 @@ pre-commit | |
| pytest-cov | ||
| flit | ||
| wheel | ||
| brotli | ||
This file contains hidden or 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
Binary file not shown.
This file contains hidden or 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,90 @@ | ||
| #!/usr/bin/env python | ||
| """ | ||
| Create a minimal PDF with Brotli compression for testing purposes. | ||
|
|
||
| This script generates a simple PDF file that uses Brotli compression | ||
| for the content stream, allowing for testing of the BrotliDecode filter | ||
| in pypdf. | ||
|
|
||
| Note: /BrotliDecode is not a standard PDF filter. This file is specifically | ||
| for testing PDF library support for this filter (e.g., in pypdf). | ||
| Standard PDF viewers will likely not render this file correctly. | ||
| """ | ||
|
|
||
| import logging | ||
| from pathlib import Path | ||
|
|
||
| import brotli | ||
|
|
||
| logging.basicConfig(level=logging.INFO, format="%(name)s: %(levelname)s: %(message)s") | ||
| logger = logging.getLogger(__name__) | ||
|
|
||
| content_stream = b"BT /F1 24 Tf 100 700 Td (Hello, Brotli!) Tj ET" | ||
| compressed_content = brotli.compress(content_stream, quality=5) | ||
|
|
||
| xref_offsets = [0] * 6 | ||
| current_offset = 0 | ||
| pdf_parts = [] | ||
|
|
||
| part = b"%PDF-1.7\n%\xc2\xa5\xc2\xb1\xc3\xab\xc3\xbf\n" # Binary marker | ||
| pdf_parts.append(part) | ||
| current_offset += len(part) | ||
| xref_offsets[1] = current_offset | ||
|
|
||
| part = b"1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n" | ||
| pdf_parts.append(part) | ||
| current_offset += len(part) | ||
| xref_offsets[2] = current_offset | ||
|
|
||
| part = b"2 0 obj\n<< /Type /Pages /Kids [3 0 R] /Count 1 >>\nendobj\n" | ||
| pdf_parts.append(part) | ||
| current_offset += len(part) | ||
| xref_offsets[3] = current_offset | ||
|
|
||
| part = ( | ||
| b"3 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] " | ||
| b"/Contents 4 0 R /Resources << /Font << /F1 5 0 R >> >> >>\nendobj\n" | ||
| ) | ||
| pdf_parts.append(part) | ||
| current_offset += len(part) | ||
| xref_offsets[4] = current_offset | ||
|
|
||
| part_header = ( | ||
| f"4 0 obj\n<< /Length {len(compressed_content)} /Filter /BrotliDecode >>\nstream\n" | ||
| ).encode("ascii") | ||
| part_footer = b"\nendstream\nendobj\n" | ||
| pdf_parts.append(part_header) | ||
| pdf_parts.append(compressed_content) | ||
| pdf_parts.append(part_footer) | ||
| current_offset += len(part_header) + len(compressed_content) + len(part_footer) | ||
| xref_offsets[5] = current_offset | ||
|
|
||
| part = b"5 0 obj\n<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>\nendobj\n" | ||
| pdf_parts.append(part) | ||
| current_offset += len(part) | ||
| xref_table_start_offset = current_offset | ||
|
|
||
| xref_lines = [b"xref\n0 6\n", b"0000000000 65535 f \n"] | ||
| xref_lines.extend( | ||
| f"{xref_offsets[i]:010d} 00000 n \n".encode("ascii") for i in range(1, 6) | ||
| ) | ||
| pdf_parts.extend(xref_lines) | ||
|
|
||
| trailer = ( | ||
| f"trailer\n<< /Size 6 /Root 1 0 R >>\nstartxref\n{xref_table_start_offset}\n%%EOF" | ||
| ).encode("ascii") | ||
| pdf_parts.append(trailer) | ||
|
|
||
| script_path = Path(__file__).resolve() | ||
| output_dir = script_path.parent / "brotli-test-pdfs" | ||
| output_path = output_dir / "minimal-brotli-compressed.pdf" | ||
|
|
||
| output_dir.mkdir(parents=True, exist_ok=True) | ||
|
|
||
| try: | ||
| with open(output_path, "wb") as f: | ||
| for part in pdf_parts: | ||
| f.write(part) | ||
| logger.info(f"Created test PDF with Brotli compression at: {output_path}") | ||
| except OSError: | ||
| logger.exception("Error writing PDF file") |
This file contains hidden or 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.
Uh oh!
There was an error while loading. Please reload this page.