Skip to content

Commit c6c25d8

Browse files
authored
ENH: Add 'strict' parameter to PDFWriter (#3503)
Closes #3494.
1 parent 4a613f3 commit c6c25d8

File tree

3 files changed

+14
-4
lines changed

3 files changed

+14
-4
lines changed

docs/user/robustness.md

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -32,8 +32,7 @@ pypdf has two core objects:
3232
* {class}`~pypdf.PdfReader`
3333
* {class}`~pypdf.PdfWriter`
3434

35-
Only the PdfReader has a `strict` parameter, since presumably you do not want
36-
to write a non-conforming PDF.
35+
PdfReader and PdfWriter both have a `strict` parameter.
3736

3837
Choosing `strict=True` means that pypdf will raise an exception if a PDF does
3938
not follow the specification.

pypdf/_writer.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -160,6 +160,10 @@ class PdfWriter(PdfDocCommon):
160160
full: If true, loads all the objects (always full if incremental = True).
161161
This parameter may allow loading large PDFs.
162162
163+
strict: If true, pypdf will raise an exception if a PDF does not follow the specification.
164+
If false, pypdf will try to be forgiving and do something reasonable, but it will log
165+
a warning message. It is a best-effort approach.
166+
163167
"""
164168

165169
def __init__(
@@ -168,7 +172,15 @@ def __init__(
168172
clone_from: Union[None, PdfReader, StrByteType, Path] = None,
169173
incremental: bool = False,
170174
full: bool = False,
175+
strict: bool = False,
171176
) -> None:
177+
self.strict = strict
178+
"""
179+
If true, pypdf will raise an exception if a PDF does not follow the specification.
180+
If false, pypdf will try to be forgiving and do something reasonable, but it will log
181+
a warning message. It is a best-effort approach.
182+
"""
183+
172184
self.incremental = incremental or full
173185
"""
174186
Returns if the PdfWriter object has been started in incremental mode.

tests/test_writer.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2867,8 +2867,7 @@ def test_wrong_size_in_incremental_pdf(caplog):
28672867
assert len(writer._objects) == 20
28682868

28692869
caplog.clear()
2870-
writer = PdfWriter(incremental=False)
2871-
writer.strict = True
2870+
writer = PdfWriter(incremental=False, strict=True)
28722871
with pytest.raises(expected_exception=PdfReadError, match=r"^Object count 19 exceeds defined trailer size 2$"):
28732872
writer.clone_reader_document_root(reader=PdfReader(BytesIO(modified_data)))
28742873

0 commit comments

Comments
 (0)